[英]Regex for matching a word within a sentence
我正在尋找一個C#正則表達式來匹配一個句子中的完整單詞。
我的句子和模式如下所示。
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);
我沒有使用上述模式的任何匹配。
但是如果我使用這種模式,我會得到一個匹配。
string mypattern = string.Format(@"\b{0}\b", "patient");
但是問題是,它也與痛苦中連字符分隔的單詞匹配,就像我在尋找完整的單詞一樣。
任何幫助表示贊賞,謝謝
方案1 (字詞前/后沒有連字符)
將否定環視(?<!-)
(否-
在搜索詞組之前)和(?!-)
(否-
在搜索詞組之后)與\\b
一起使用:
var mypattern = string.Format(@"(?<!-)\b{0}\b(?!-)", Regex.Escape(search));
場景2 (用空格括起來的單詞)
我想匹配一個單詞,可以在換行符或空格之后或之前。
您需要使用類似的環顧:
var mypattern = string.Format(@"(?<!\S){0}(?!\S)", Regex.Escape(search));
(?<!\\S)
環顧(等於(?<=\\s|^)
)在搜索詞之前需要空格或字符串開頭。 (?!\\S)
否定的超前搜索將在搜索詞后需要一個空格符號。
Regex.Escape
是警告步驟,請確保搜索詞中的所有特殊字符均被視為文字字符。
注意:如果您的“單詞”從不包含空格,則不需要正則表達式。 采用
var search = "this";
var sentence = "There is no gain in this world without pain";
var isPresent = sentence.Split().Contains(search);
Console.Write(isPresent); // = > True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.