3

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?

2 Answers 2

8

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']
>>>
Sign up to request clarification or add additional context in comments.

2 Comments

In [101]: re.findall("[(.*?)]", string) Out[101]: ['5', '6', '10', '100:', '-2:', '-2'] works.
@kracekumar - The code in your comment does not work (it returns an empty list). The code in your answer does work, but you should mention that it will get everything that is inside square brackets. For the OP's sample, this is fine, but it may not be appropriate behavior elsewhere.
1

Modifying iCodez answer a bit.

In [102]: import re

In [103]: string = "List[5] List[6], List[10], List[100:] List[-2:] List[-2]"

In [105]: re.findall("\[(.*?)\]", string)
Out[105]: ['5', '6', '10', '100:', '-2:', '-2']

Above will extract any character inside square bracket. If the string contains List[5] Add[3] output will be [5, 6]

In [115]: string = "List[4] tuple[3]"

In [116]: re.findall("\[(.*?)\]", string)
Out[116]: ['4', '3']

Above method will extract any characters inside square bracket.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.