[英]REGEX to check for phrase within first 25 characters
I'm using regular expressions to match a keyword. 我正在使用正则表达式来匹配关键字。 Is it possible to check for this keyword within ONLY the first 25 characters?
是否可以仅在前25个字符内检查此关键字?
For example, I want to find "APPLE"
: 例如,我想找到
"APPLE"
:
'Johnny picked an APPLE from the tree'
- Match Found (within first 25 chars) 'Johnny picked an APPLE from the tree'
-找到匹配项(前25个字符以内)
'Johnny picked something from a tree that had an APPLE'
- Not Found (because APPLE does not exist within the first 25 chars). 'Johnny picked something from a tree that had an APPLE'
-未找到(因为在前25个字符中不存在'Johnny picked something from a tree that had an APPLE'
)。
Is there syntax for this? 有语法吗?
Yes it is. 是的。 You prefix your keyword with zero to 25 - length(keyword) "any" characters.
您为关键字加上0到25-长度(关键字)“ any”个字符的前缀。
I'm not sure if this is actual python syntax, but the RE should be ^.{0,20}APPLE
. 我不确定这是否是真正的python语法,但RE应该是
^.{0,20}APPLE
。
Edit: for clarification 编辑:为澄清
^.{0,20}APPLE
should be used when looking for a substring. ^.{0,20}APPLE
。 Use this in Python. .{0,20}APPLE.*
should be used when matching the whole string. .{0,20}APPLE.*
。 Another edit: Apparently Python only has substring mode, so the ^
anchor is necessary. 另一个编辑:显然,Python仅具有子字符串模式,因此
^
锚是必需的。
Try using a slice on your string: 尝试在字符串上使用切片 :
>>> 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.