简体   繁体   English

python regex句子的结尾或开头

[英]python regex end or beginning of a sentence

I have code as below. 我有如下代码。 I want to find cases where word "eve" is present 我想查找单词“ eve”存在的情况

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 . 下面的代码找到['eve?', 'eve ']但是找不到最后一个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 我在下面的代码中尝试过尝试在“ eve”之后进行编码,可能是\\b[^a-zA-Z\\d:]但是它没有用

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 (?<![a-zA-Z\\d])之前添加(?![a-zA-Z\\d])
  2. add (?:^|(?<=\\s)) before 在前面加上(?:^|(?<=\\s))
  3. add (?:$|(?=[^a-zA-Z\\d])) after (?:$|(?=[^a-zA-Z\\d]))之后

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何正则表达式的开头和结尾 - python - How to regex the beginning and the end of a sentence - python Python Regex-根据开头和结尾捕获句子 - Python Regex - Capturing a sentence based on the beginning and ending 正则表达式匹配 python 中文件开头或结尾的空格 - Regex to match space in the beginning or end of file in python 在python中匹配字符串的开头和结尾与正则表达式 - Match beginning and end of string with regex in python Python Regex在开始时就可以匹配,但在结尾时不起作用 - Python Regex works for match at the beginning, but not at end Python REGEX忽略句子开头的大小写,并接受其余部分 - Python REGEX ignore case at the beginning of the sentence and take the rest Python正则表达式如何删除以 - 开头并以逗号结尾的句子末尾的字符串? - Python regex how to remove string at the end of sentence that starts with - and ends with a comma? "Python 正则表达式检查子字符串是在要查找的更大路径的开头还是结尾" - Python regex to check if a substring is at the beginning or at the end of a bigger path to look for Python regex - 去掉开头和结尾并保留中间部分不变 - Python regex - strip out beginning and end and leave middle untouched python regex匹配并替换字符串的开头和结尾,但保持中间 - python regex match and replace beginning and end of string but keep the middle
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM