0

I am struggling to find a solution for matching two successive whole words using Regular Expression. I have a text box where the user can type in their search criteria, enclosed by quotations for exact matches. The quotes and space (if any) are then replaced by RegEx expressions. Here is an example:

User enters: "Apple Orange"

Converted to:

\bApple\W+(?:\w+\W+){1,6}?Orange\b

Then, my RegEx match would be based on this converted criteria. The instructions are from www.regular-expressions.info/near.html

Maybe I am going about this entirely the wrong way? I am using visual studio. Any help is appreciated.

4

1 回答 1

2

如果您在用户使用引号时想要完全匹配,那么您应该删除引号并进行直接字符串比较(相等,不包含)

更新:

根据下面的评论,您只需执行与单个单词匹配相同的操作:

一个字:

\bApple\b

双字

\bApple Orange\b

这个想法是用户输入搜索词并且您完全匹配,因此您不会为该词本身进行模式匹配,只是它的边界(\b围绕它)。没有理由触及搜索词本身(Apple 和 Orange 之间的所有你试图做的东西),因为即使两者之间的空间也是他们搜索的一部分......除非你想要让它有点灵活..例如,如果用户输入"Apple[lots of space here]Orange"只是将其视为一个空格,那么您可以这样做

\bApple\s+Orange\b

..但是你有点偏离了整个“完全匹配”的主题......

旁注:您在评论中说,对于“CrabApple OrangeCrush”,您不希望“Apple Orange”匹配。这就是你使用\b边界这个词的原因。但如果是我,IMO 会允许它匹配。或者至少,提供某种选项以这种方式搜索它。

于 2013-04-25T13:46:41.207 回答