[英]python regex with conditional lookbehind
I'm looking for substring starting with @
and ending with the first \\s
occurrence. 我在寻找与子串开始
@
,并与第一结束\\s
发生。 It's necessary to have @
at the beginning of the string or after space. 必须在字符串的开头或空格之后使用
@
。
Example : @one bla bla bla @two @three@four #@five
例如 :
@one bla bla bla @two @three@four #@five
Result : @one, @two, @three@four
结果 :
@one, @two, @three@four
I end up with this re: ((?<=\\s)|(?<=^))@[^\\s]+
which works fine in sublime text 2, but returns empty strings in python. 我最终得到了这个:
((?<=\\s)|(?<=^))@[^\\s]+
在sublime文本2中工作正常,但在python中返回空字符串。
python code : python代码 :
re.findall(r'((?<=^)|(?<=\s))@[^\s]+', '@one bla bla bla @two @three@four #@five')
if you are willing not to use reg expr you could try: 如果你不愿意使用reg expr你可以尝试:
>>> s ="@one bla bla bla @two @three@four #@five"
>>> filter(lambda x:x.startswith('@'), s.split())
['@one', '@two', '@three@four']
This actually should be much faster... 这实际上应该快得多......
Your capturing group isn't capturing the text that you are really looking for: 您的捕获组未捕获您正在寻找的文本:
(?:(?<=^)|(?<=\s))(@[^\s]+)
Now, it works: 现在,它有效:
>>> re.findall(r'(?:(?<=^)|(?<=\s))(@[^\s]+)', '@one bla bla bla @two @three@four #@five')
['@one', '@two', '@three@four']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.