C# 用于匹配句子中的单词的正则表达式

C# 用于匹配句子中的单词的正则表达式,c#,regex,C#,Regex,我正在寻找一个C#regex来匹配一个句子中的完整单词 我的句子和句型如下所示 string mySentence = "There is no gain in this world without pain"; string mypattern = string.Format(@"(?:(?<=^|\s)(?=\S)|(?<=\S|^)(?=\s)){0} (?:(?<=\S)(?=\s|$)|(?<=\s)(?=\S|$))", "pain"); Match

我正在寻找一个C#regex来匹配一个句子中的完整单词

我的句子和句型如下所示

 string mySentence = "There is no gain in this world without pain";

 string mypattern = string.Format(@"(?:(?<=^|\s)(?=\S)|(?<=\S|^)(?=\s)){0} (?:(?<=\S)(?=\s|$)|(?<=\s)(?=\S|$))", "pain");

 MatchCollection matches = Regex.Matches(mySentence, mypattern);
但问题是它也匹配连字符分隔的单词,比如在痛苦中,我在寻找一个完整的单词

感谢您的帮助

场景#1(单词前面/后面没有连字符)

在搜索短语之前使用否定环视(?(无
-
)和
(?!-)
(无
-
)以及
\b

var mypattern = string.Format(@"(?<!-)\b{0}\b(?!-)", Regex.Escape(search));

等等,实际要求是什么?匹配一个包含空格的搜索短语?或者在单词边界内,但不在前面/后面加
-
?@WiktorStribiżew我想匹配一个单词,后面或前面可以加换行符或空格。谢谢,我提供了这两种解决方案,以及一个非正则表达式的解决方案你只需要在更长的字符串中搜索非空白文本块。我尝试了这句话,毫无疑问会有收获。但我没有找到匹配项,我想我忘了告诉你后面可能有句点或任何特殊字符,所以,
var mypattern=string.Format(@)(?我认为场景1中的正则表达式适合我:)-谢谢我试过这句话,这个世界上没有痛苦就没有痛苦。在这里,它代表了我的痛苦,有没有办法,我只匹配痛苦的发生而不是痛苦的发生?我想它将是
(?![''-)
。如果你在搜索词中加上引号,你会得到错误的否定。
var mypattern = string.Format(@"(?<!-)\b{0}\b(?!-)", Regex.Escape(search));
var mypattern = string.Format(@"(?<!\S){0}(?!\S)", Regex.Escape(search));
var search = "this";
var sentence = "There is no gain in this world without pain";
var isPresent = sentence.Split().Contains(search);
Console.Write(isPresent); // = > True