[英]How to find a word directly after another word in a string C#
我正在嘗試查找字符串是否包含單詞,在我的情況下是單詞“Message”,然后如果它包含該單詞,則直接在它之后查找單詞。 到目前為止,我的相關代碼如下。
public bool Find(string Word,string Text)
{
return Text.Contains(Word);
}
然后它以各種方式使用 function 但為此特定目的它需要找到“消息”如下
if (Find("Message", MessageText))
{
//I don't know what to put here
}
我需要獲取字符串 MessageText 然后在字符串中找到 Message 然后 output 單詞 Message 之后的第一個單詞。 例如“任何隨機字符串消息布拉德和更多隨機字符串”我想要 output 布拉德
利用
var word = "someword";
var regex = new Regex(string.Format(@"(?<!\w){0}\W+(\w+)", Regex.Escape(word)));
var match = regex.Match(text);
if (match.Success)
{
Console.WriteLine(match.Groups[1].Value);
}
Regex.Escape(word)
是在word
包含+
, [
, (
或其他特殊字符的情況下。 (?<!\w)
優於\b
,因為即使word
以特殊字符開頭,它也會正確匹配。 \W+
是比\s+
更好,因為它匹配兩個單詞之間的任何非單詞字符。
請參閱正則表達式證明。
解釋
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
\w word characters (a-z, A-Z, 0-9, _)
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
Message 'Message'
--------------------------------------------------------------------------------
\W+ non-word characters (all but a-z, A-Z, 0-
9, _) (1 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
如果我們可以假設您的話被大寫/小寫更改以外的其他內容打斷,我會使用以下內容:
var regex = new Regex(string.Format(@"\b{0}\b\s+(?<nextWord>\w+)", word));
var match = regex.Match(text);
return match.Groups["nextWord"].Value;
我創建了一個 dotnetfiddle 來演示: https://dotnetfiddle.net/ypXYpQ
\b 塊正在尋找單詞邊界,所以我在其中兩個之間注入單詞,用 \s+ 塊查找 1 個或多個空白字符,然后使用 \w+ 塊捕獲word
字符。 該代碼還演示了如何從 function(或您接下來需要做的任何事情)中獲取下一個單詞並返回它。
我首先使用regex101.com 使這個表達式起作用。 這是一個出色的工具,可以解釋正則表達式的工作原理,為您提供可搜索的快速參考,並讓您保存和創建表達式測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.