简体   繁体   中英

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)

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']

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)

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