[英]Python Regex doesn't match . (dot) as a character
我有一个匹配字符串中所有三个字符的正则表达式:
\b[^\s]{3}\b
当我将它与字符串一起使用时:
And the tiger attacked you.
这是结果:
regex = re.compile("\b[^\s]{3}\b")
regex.findall(string)
[u'And', u'the', u'you']
你可以看到它与三个字符的单词匹配,但我希望表达式取“你”。 用“。” 作为4个字符。
我对“,”,“;”,“:”等有同样的问题。
我对正则表达式很新,但我想这是因为这些字符被视为字边界。
有办法做到这一点吗?
提前致谢,
想知道@BrenBarn和@Kendall Frey的答案我设法得到了我正在寻找的正则表达式:
(?<!\w)[^\s]{3}(?=$|\s)
如果您想确保单词前面和后面跟一个空格(而不是像您的情况那样的句号),那么请使用环视 。
(?<=\s)\w{3}(?=\s)
如果你需要它来匹配标点符号作为单词的一部分(例如'in。')那么\\w
就不够了,你可以使用\\S
(除了空格之外的任何东西)
(?<=\s)\S{3}(?=\s)
这将是我的方法。 也匹配标点符号后面的单词。
import re
r = r'''
\b # word boundary
( # capturing parentheses
[^\s]{3} # anything but whitespace 3 times
\b # word boundary
(?=[^\.,;:]|$) # dont allow . or , or ; or : after word boundary but allow end of string
| # OR
[^\s]{2} # anything but whitespace 2 times
[\.,;:] # a . or , or ; or :
)
'''
s = 'And the tiger attacked you. on,bla tw; th: fo.tes'
print re.findall(r, s, re.X)
输出:
['And', 'the', 'on,', 'bla', 'tw;', 'th:', 'fo.', 'tes']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.