[英]REGEX to check for phrase within first 25 characters
我正在使用正则表达式来匹配关键字。 是否可以仅在前25个字符内检查此关键字?
例如,我想找到"APPLE"
:
'Johnny picked an APPLE from the tree'
-找到匹配项(前25个字符以内)
'Johnny picked something from a tree that had an APPLE'
-未找到(因为在前25个字符中不存在'Johnny picked something from a tree that had an APPLE'
)。
有语法吗?
一个简单的解决办法是将切断25个第一字符,然后执行正则表达式匹配。
myString = 'Johnny picked an APPLE from the tree'
slicedString = myString[:25]
# do regex matching on slicedString
是的。 您为关键字加上0到25-长度(关键字)“ any”个字符的前缀。
我不确定这是否是真正的python语法,但RE应该是^.{0,20}APPLE
。
编辑:为澄清
^.{0,20}APPLE
。 在Python中使用它。 .{0,20}APPLE.*
。 另一个编辑:显然,Python仅具有子字符串模式,因此^
锚是必需的。
尝试在字符串上使用切片 :
>>> import re
>>> string1 = "Johnny picked an APPLE from the tree"
>>> string2 = "Johnny picked something from a tree that had an APPLE"
>>> re.match(".*APPLE.*", string1[:25]) # Match
<_sre.SRE_Match object at 0x2364030>
>>> re.match(".*APPLE.*", string2[:25]) # Does not match
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.