Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re/regex pattern for string python

Tags:

python

regex

I'm trying to figure out a regex pattern to find all occurrences in a string for this:

string = "List[5] List[6], List[10], List[100:] List[-2:] List[-2]"
re.findall("List[(.*?)]" , string)
# Expected output ['5', '6', '10', '100:',  '-2:', '-2']
# Output: []

What would be a good regex pattern to get the numbers in between the indexes?

like image 867
user2925490 Avatar asked Jan 31 '26 07:01

user2925490


1 Answers

Square brackets are special characters in Regex's syntax. So, you need to escape them:

>>> import re
>>> string = "List[5] List[6], List[10], List[100:] List[-2:] List[-2]"
>>> re.findall("List\[(.*?)\]", string)
['5', '6', '10', '100:', '-2:', '-2']
>>>