Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 正则表达式是否匹配整个单词?_.net_Regex_Match - Fatal编程技术网

.net 正则表达式是否匹配整个单词?

.net 正则表达式是否匹配整个单词?,.net,regex,match,.net,Regex,Match,关于我的问题, 我得到的答案是 @"(?<=^|\s)" + pattern + @"(?=\s|$)" (?试试这个 (?:(?<=^|\s)(?=\S)|(?<=\S|^)(?=\s))this (?:(?<=\S)(?=\s|$)|(?<=\s)(?=\S|$)) 更新: string str = "Hi this is stackoverflow"; string pattern = Regex.Escape("this"); MatchCollecti

关于我的问题,

我得到的答案是

@"(?<=^|\s)" + pattern + @"(?=\s|$)"
(?试试这个

(?:(?<=^|\s)(?=\S)|(?<=\S|^)(?=\s))this (?:(?<=\S)(?=\s|$)|(?<=\s)(?=\S|$))
更新:

string str = "Hi this is stackoverflow";
string pattern = Regex.Escape("this");
MatchCollection result = Regex.Matches(str, @"(?:(?<=^|\s)(?=\S)|(?<=\S|^)(?=\s))" + pattern + @"(?:(?<=\S)(?=\s|$)|(?<=\s)(?=\S|$))", RegexOptions.IgnoreCase);

Console.WriteLine("Amount of matches: " + result.Count);
foreach (Match m in result)
{
    Console.WriteLine("Matched: " + result[0]);
}
Console.ReadLine();
这个“空白”边界可以做得更一般,这样在模式的每一侧都有相同的表达式,如下所示

(?:(?<=^|\s)(?=\S|$)|(?<=^|\S)(?=\s|$))

(?:(?您不能简单地从调用层修剪模式吗?假设这是用户输入,您可以在将其发送到服务层之前修剪用户输入。在几乎所有情况下都有效,但在匹配字符串(如“c++c”中的“c++c”)时失败#“C++ C++ C++,什么是失败?对我来说它工作得很好,我看不出一个原因,为什么它不应该与C++类似。它匹配如果你匹配C++,但是如果你在文本“c+c+c````@ PRATZ”中匹配“c++c”,那就要看你使用的模式了……它不被这个问题所覆盖。两个词。你这里的答案非常有用。它适用于“c++”,但它与“c++”之类的词不匹配。它是一个完整的词(结尾有一个空格),我不认为问题中没有涉及它有什么意义。肯定会有这样的情况。
MatchCollection result = Regex.Matches(str, @"(?:(?<=^|\s)(?=\S|$)|(?<=^|\S)(?=\s|$))" + pattern + @"(?:(?<=^|\s)(?=\S|$)|(?<=^|\S)(?=\s|$))", RegexOptions.IgnoreCase);