Reputation: 6756
I have code as below. I want to find cases where word "eve" is present
My conditions are
there shouldn't be any numbers or alphabets after or before "eve"
before 'eve' there could be a space or nothing
after 'eve' there could be symbols or nothing
below code finds ['eve?', 'eve ']
but fails to find the last eve
. How should I change the code
import re
your_string = "eve? is a rule, but not evening and not never. eve eve"
re.findall(r'\beve[^a-zA-Z\d:]', your_string)
I tried below code
where i am trying to code that after 'eve' there could be either \b
or [^a-zA-Z\d:]
but it didnt work
import re
your_string = "eve? is a rule, but not evening and not never. eve eve"
re.findall(r'\beve(\b|[^a-zA-Z\d:])', your_string)
Upvotes: 0
Views: 223
Reputation: 19315
Conditions are redundant, but may be translared into regex, and can be used together,:
(?<![a-zA-Z\d])
before and (?![a-zA-Z\d])
after(?:^|(?<=\s))
before(?:$|(?=[^a-zA-Z\d]))
afterupdated with code
import re
your_string = "eve? is a rule, but not evening and not never. eve eve"
re.findall(r'(?<![a-zA-Z\d])(?:^|(?<=\s))eve(?![a-zA-Z\d])(?:$|(?=[^a-zA-Z\d]))', your_string)
Upvotes: 0
Reputation: 91385
Use word boundary on each side:
import re
your_string = "eve? is a rule, but not evening and not never. eve eve"
print re.findall(r'\beve\b', your_string)
Output:
['eve', 'eve', 'eve']
Upvotes: 3