简体   繁体   English

C#RegEx查找字符串中的特定字符串或所有单词

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

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.
}

Just remove the second \\ in the first @"\\b\\" : 只需删除第一个@"\\b\\"中的第二个\\

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

See IDEONE demo 请参阅IDEONE演示

Note that in case you have special regex metacharacters (like ( , ) , [ , + , * , etc.) in your searchString s, you can use Regex.Escape() to escape them: 请注意,如果您的searchString有特殊的正则表达式元字符(如()[+*等),则可以使用Regex.Escape()来转义它们:

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)";

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

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