Reputation: 1688
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?
Upvotes: 0
Views: 260
Reputation: 154
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
Upvotes: 7
Reputation: 909
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
Upvotes: 1
Reputation: 2121
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.
Upvotes: 2