在正则表达式中是否有方法检查某个单词是否出现在两个已定义位置之一的字符串中?

2024-06-28 19:45:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,例如:myString = "word1 word2 word3"。我想创建一个正则表达式来检查word3是否代替word1或word3。我尝试使用问号(可选),但即使字符串中没有出现该单词,也会匹配。我希望单词位于字符串中的两个位置之一(例如word1和word3)。有没有办法做到这一点?我不是很擅长正则表达式,任何帮助将不胜感激

str = "word3 word1 word2"  # Should match
str2 = "word3 word2 word3"  # Should not match
str3 = "word1 word3 word2"  # Should not match
str4 = "word1 word2 word2"  # Should not match

str4在我使用"(word3)? [\w\s] (word3)?"时匹配。任何帮助都会很好。提前谢谢你


Tags: 字符串matchnot单词shouldstr办法mystring
3条回答

正则表达式Try(?m)^(?:(word3)\s+\w+\s+(?!\1\b)\w+|(?!word3\b)\w+\s+\w+\s+word3)$

demo

如果word3只能出现在第一位或第三位,并且中间的单词可以是任何单词字符,那么一种选择是对两种场景使用带有alternation的负前瞻(?!

^(?:word3 \w+ (?!word3$)\w+|(?!word3 )\w+ \w+ word3)$

解释

  • ^字符串的开头
  • (?:非捕获组
    • word3 \w+ 匹配word3空格1+单词字符和空格
    • (?!word3$)负向前看,断言直接在右边的不是紧跟字符串末尾的word3
    • \w+如果前面的断言为true,则匹配1+单词字符
    • |
    • (?!word3 )负向前看,断言右边不是紧跟空格的单词3
    • \w+ \w+ word3匹配1+字字符、空格1+字字符空格和word3
  • )关闭组
  • $字符串的结尾

Regex demoPython demo

示例代码

import re

strings = [
    "word1 word2 word3",
    "word3 word1 word2",
    "word3 word3 word2",
    "word3 word2 word3",
    "word1 word3 word2",
    "word1 word2 word2"
];

pattern = r"(?:word3 \w+ (?!word3$)\w+|(?!word3 )\w+ \w+ word3)"
r = re.compile(pattern)
for s in strings:
    print (bool(r.match(s)))

输出

True
True
True
False
False
False

我已经解决了一个更一般的问题:给定一个包含两个或多个单词的字符串,请验证第一个或最后一个单词是否为word3,第一个和最后一个单词是否都为word3,并且字符串的开头或结尾没有空格。如果需要确认字符串包含三个单词,则必须进行单独的检查,例如r"^\w+(?: +\w+){2}$"

您可以使用以下正则表达式

r"^(?:word3 (?!.* word3$)|(?!word3 ).* word3$)"

Regex demo<“”\_(ツ)_/'>;Python demo

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

^                match beginning of line
(?:              begin non-capture group
  word3[ ]       match 'word3' followed by a space
  (?!.* word3$)  the space is not to be followed by ' word3' at
                 the end of the line
|                or
  (?!word3 )     do not match 'word3 ' at the beginning of the line
  .*             match 0+ chars
  [ ]word3$      match ' word3' at the end of the line 
)                end non-capture group

(?!...)是一个负的前瞻。在上面我用[ ]替换了两个空格,以免它们看起来丢失

相关问题 更多 >