繁体   English   中英

正则表达式匹配后跟空格或标点符号的单词

[英]Regex to match words followed by whitespace or punctuation

如果我有india这个词

匹配"india." "india!" "india." "india" "india." "india!" "india." "india"

不匹配"indian" "indiana"

基本上,我想匹配字符串,但不是当它包含在另一个字符串中时。

在做了一些研究之后,我开始

exp = "(?<?\S)india(.!\S)" num_matches = len(re.findall(exp))

但这与标点符号不匹配,我不确定在哪里添加。

假设目标是匹配字符串中的给定单词(例如"india" ),前提是该单词的前面和后面都没有不在字符串".,?;;"中的字符。 您可以使用以下正则表达式:

(?<![^ .,?!;])india(?![^ .,?!;\r\n])

演示

Python 的正则表达式引擎执行以下操作

(?<!             # begin a negative lookbehind
  [^ .,?!;]      # match 1 char other than those in " .,?!;"
)                # end the negative lookbehind
india            # match string
(?!              # begin a negative lookahead   
  [^ .,?!;\r\n]  # match 1 char other than those in " .,?!;\r\n"
)                # end the negative lookahead

请注意,如果india位于行尾,则负前瞻中的字符 class 包含\r\n

尝试:

r'\bindia\W*\b'

查看演示


忽略大小写:

re.search(r'\bindia\W*\b', my_string, re.IGNORECASE).group(0)

你可以使用:

import re

s = "india."
s1 = "indiana"
print(re.search(r'\bindia[.!?]*\b', s))
print(re.search(r'\bindia[.!?]*\b', s1))

output:

<re.Match object; span=(0, 5), match='india'>
None
\"india(\W*?)\" 

这将捕获除数字和字母之外的任何内容

试试这个^india[^a-zA-Z0-9]$

^ - 正则表达式从印度开始

[^a-zA-Z0-9] - 不是 az, AZ, 0-9

$ - 结束正则表达式

如果您还想匹配标点符号,您可以使用否定字符 class来匹配除单词字符或换行符之外的任何字符。

(?<!\S)india[^\w\r\n]*(?!\S)
  • (?<!\S)在左边断言一个空白边界
  • india从字面上匹配
  • [^\w\r\n]匹配除单词 char 或换行符以外的任何字符 0+ 次
  • (?!\S)断言右边的空白边界

正则表达式演示

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM