试图指定我的捕获组,但它继续捕获太多.
线:
"This is something of [Interest: stuff]. blah blah blah"
Run Code Online (Sandbox Code Playgroud)
正则表达式:
patt = re.compile('\[Interest:(.){1,100}\]')
Run Code Online (Sandbox Code Playgroud)
什么是输出:
[Interest: stuff]
Run Code Online (Sandbox Code Playgroud)
我想要的输出:
stuff
Run Code Online (Sandbox Code Playgroud)
如何输出我想要捕获的内容,而不是整个模式?
我也试过这个:
re.compile(r'\[Interest:(?P<interest>.+)\]')
Run Code Online (Sandbox Code Playgroud)
那输出:
stuff]. blah blah blah
Run Code Online (Sandbox Code Playgroud)
我觉得我很亲密.只需要弄清楚一旦正则表达式击中后如何停止输出]
该.字符匹配除换行符,包括一切].因此,(.){1,100}正在告诉Python将所有内容都放到100字符上.这包括字符串的结尾.
相反,我会使用这种模式:
\[Interest:\s([^\]]*)\]
Run Code Online (Sandbox Code Playgroud)
演示:
>>> import re
>>> string = "This is something of [Interest: stuff]. blah blah blah"
>>> re.search("\[Interest:\s([^\]]*)\]", string).group(1)
'stuff'
>>>
Run Code Online (Sandbox Code Playgroud)
以下是它匹配的解释:
\[ # [
Interest: # Interest:
\s # A space
( # The start of a capture group
[^\]]* # Zero or more characters that are not ]
) # The close of the capture group
\] # ]
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅正则表达式语法.
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |