简体   繁体   中英

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?

For example, I want to find "APPLE" :

'Johnny picked an APPLE from the tree' - Match Found (within first 25 chars)

'Johnny picked something from a tree that had an APPLE' - Not Found (because APPLE does not exist within the first 25 chars).

Is there syntax for this?

A simple solution would be to slice off the 25 first characters and then do the regex matching.

myString = 'Johnny picked an APPLE from the tree'
slicedString = myString[:25]
# do regex matching on slicedString

Yes it is. You prefix your keyword with zero to 25 - length(keyword) "any" characters.

I'm not sure if this is actual python syntax, but the RE should be ^.{0,20}APPLE .

Edit: for clarification

  • ^.{0,20}APPLE should be used when looking for a substring. Use this in Python.
  • .{0,20}APPLE.* should be used when matching the whole string.

Another edit: Apparently Python only has substring mode, so the ^ anchor is necessary.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM