字符串python的re / regex模式

时间:2013-12-15 18:44:32

标签: python regex

我正在试图找出一个正则表达式模式来查找字符串中的所有匹配项:

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: []

在索引之间获取数字会有什么好的正则表达式模式?

2 个答案:

答案 0 :(得分:8)

方括号是Regex's syntax中的特殊字符。所以,你需要逃脱它们:

>>> 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']
>>>

答案 1 :(得分:1)

稍微修改iCodez回答。

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']

上面将提取方括号内的任何字符。如果字符串包含List[5] Add[3]输出,则为[5, 6]

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

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

上面的方法将提取方括号内的任何字符。

相关问题