[英]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.