正则表达式匹配不属于较大单词的字符串

时间:2019-07-04 14:49:23

标签: c# regex

我很困惑如何解决这个问题。

我正在尝试匹配字符串“ ashi”,但是如果包含单词的单词在一小部分已知的误报中(例如“闪烁”,“绑扎”,“砸”),则不会匹配。假阳性词可以出现在字符串中,只要字符串“ ashi”(不是假阳性词之一的一部分)出现在字符串中,它就应该返回true。

我正在使用C#,并且尝试不使用正则表达式进行处理,但是我没有运气。

这些字符串应返回true

...somethingashisomething...

...something2!ashi*&something... 

... something ashi something flashing...

这些字符串应返回false

...somethingflashingsomething...

...smashingthesomething...

...the lashings are too tight...   

4 个答案:

答案 0 :(得分:2)

以下内容将与ashi相匹配,但不在flashing之内。我松散地解释了“单词”,因此不需要flashing作为带有空格/标点分隔符的单独单词来隔离。

(?<=(?<prefix>fl)|)ashi(?(prefix)(?!ng))

在整个模式中返回true / false就足够了,不需要检查特定的捕获组。换句话说,它可以与Regex.IsMatch()一起使用。

模式详细信息:

(?<=               # Zero-width positive lookbehind: match but don't consume characters
  (?<prefix>fl)    # Named capture group to match "fl" at start of "flashing"
  |                # Alternate blank capture - will succeed if "fl" is not present
)                  # End lookbehind
ashi               # match literal "ashi"
(?(prefix)         # Conditional:  Only match if named group prefix has successful capture (i.e. "fl" was matched)
  (?!ng)           # Zero-width negative loohahead: Fail match if "ng" follows 
)                  # Close conditional (there is no false part, so match succeeds if "fl" was not present)

如果仅将flashing作为一个孤立单词排除,则只需添加单词边界运算符即可。这将与flashingwithnospace之类的内容匹配,而第一个模式将对该字符串失败:

(?<=(?<prefix>\bfl)|)ashi(?(prefix)(?!ng\b))

(仅供参考,该模式将单独工作,但是如果将其组合在另一个模式中,尤其是在重复构造中,则由于命名捕获组的条件而可能无法工作。一旦命名捕获组成功完成,即使匹配另一个ashi,条件也会匹配更大的模式时保持为真。)

答案 1 :(得分:2)

另一种选择是使用带有嵌套前瞻的否定性后向匹配以fl开头的单词,但如果后面跟ashing匹配ashi而不匹配{{ 1}}。

flashing

说明

  • (?<!\bfl(?=ashing\b))ashi 负向后看,断言直接在右边的不是
    • (?<!单词边界,匹配\bfl
    • fb正向前进,断言右边直接是
      • (?=匹配灰化和单词边界
    • ashing\b积极回望
  • )近距离观看。
  • )字面上匹配

.NET Regex demo

更新

如果您要匹配而不匹配更新后的值,则可以在后面的负数后面使用替代项ashi来匹配(?:sm|f?l)或可选的sm,后跟{{1} }

f

.NET regex demo | C# demo

答案 2 :(得分:1)

您可以使用一个捕获组:

(flashing)|ashi

如果第一组不为空,则您在字面上匹配了flashing

答案 3 :(得分:0)

问题举了例子

...somethingashisomething...
...something2!ashi*&something...
... something ashi something...

第二个和第三个示例可以通过在搜索(即搜索\b)中包括单词边界\bashi\b来找到。找到第一个示例需要更多了解两个封闭的something是什么。如果它们是字母数字,那么您需要更详细地说明问题。

相关问题