C# RegEx to find a specific string or all words in a string

社会主义新天地 提交于 2021-02-07 14:43:06

问题


Looking it up, I thought I understood how to look up a string of multiple words in a sentence, but it does not find a match. Can someone tell me what I am doing wrong? I need to be able to find a single or multiple word match. I passed in "to find" to the method and it did not find the match. Also, if the user does not enclose their search phrase in quotes, I also need it to search on each word entered.

var pattern = @"\b\" + searchString + @"\b";    //searchString is passed in.

Regex rgx = new Regex(pattern);

var sentence = "I need to find a string in this sentence!";

Match match = rgx.Match(sentence);

if (match.Success)
{
    // Do something with the match.
}

回答1:


Just remove the second \ in the first @"\b\":

var pattern = @"\b" + searchString + @"\b";
                  ^

See IDEONE demo

Note that in case you have special regex metacharacters (like (, ), [, +, *, etc.) in your searchStrings, you can use Regex.Escape() to escape them:

var pattern = @"\b" + Regex.Escape(searchString) + @"\b";

And if those characters may appear in edge positions, use lookarounds rather than word boundaries:

var pattern = @"(?<!\w)" + searchString + @"(?=\w)";


来源:https://stackoverflow.com/questions/33726629/c-sharp-regex-to-find-a-specific-string-or-all-words-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!