[英]Detecting a word followed by a dot or whitespace using regex
我使用regex
和C#
來查找特定單詞的出現次數
Regex regex = new Regex(@"\b" + word + @"\b");
我如何修改我的正則表達式只檢測單詞,如果它前面有一個空格,后跟一個空格或后跟一個點?
例子:
this.Button.Value - 應該匹配this.value - 應該匹配
document.thisButton.Value - 不應該匹配
Regex regex = new Regex(@"((?<=( \.))" + word + @"\b)" + "|" + @"(\b" + word + @"[ .])");
但請注意,如果word
包含在正則表達式中具有特殊含義的字符,則可能會導致問題。 我假設該word
僅包含字母數字字符。
如果我正確理解你:
Regex regex = new Regex(@"\b" + (word " " || ".") + @"\b");
當關鍵字用空格括起或者后跟一個點時,您可以使用外觀和替換來檢查兩種可能性:
var line = "this.Button.Value\nthis.value\ndocument.thisButton.Value";
var word = "this";
var rx =new Regex(string.Format(@"(?<=\s)\b{0}\b(?=\s)|\b{0}\b(?=\.)", word));
var result = rx.Replace(line, "NEW_WORD");
Console.WriteLine(result);
模式匹配:
(?<=\\s)\\bthis\\b(?=\\s)
- 整個單詞“this”前面有空格(?<=\\s)
,后跟空格(?=\\s)
|
- 要么 \\bthis\\b(?=\\.)
- 整個單詞“this”后跟一個文字.
( (?=\\.)
) 由於lookarounds不消耗字符(正則表達式索引保持原樣),與它們匹配的字符不會放在匹配值中,因此在替換期間不會受到影響。
的(?<=...)
匹配組檢查前和(?=...)
檢查以下,既沒有將它們包括在匹配。
Regex regex = new Regex(@"(?<=\s)\b" + word + @"\b|\b" + word + @"\b(?=[\s\.])");
編輯:模式更新。
編輯2:在線測試: http : //ideone.com/RXRQM5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.