user2543622
user2543622

Reputation: 6756

python regex end or beginning of a sentence

I have code as below. I want to find cases where word "eve" is present

My conditions are

  1. there shouldn't be any numbers or alphabets after or before "eve"

  2. before 'eve' there could be a space or nothing

  3. 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

Answers (2)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

Conditions are redundant, but may be translared into regex, and can be used together,:

  1. add (?<![a-zA-Z\d]) before and (?![a-zA-Z\d]) after
  2. add (?:^|(?<=\s)) before
  3. add (?:$|(?=[^a-zA-Z\d])) after

updated 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

Toto
Toto

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

Related Questions