簡體   English   中英

正則表達式匹配單詞的開頭但替換整個單詞

[英]Regex match the start of a word but replace the whole word

我想搜索所有以模式開頭的單詞,然后用另一個文本替換整個單詞。 我看到我們只能進行整個單詞匹配並替換它,但沒有找到匹配開頭並替換整個單詞的方法。

string input = "My name is ABCDEFG and not ABCDQWER"
string pattern = @"\bABCD";
string replace = "text";
string result = Regex.Replace(input, pattern, replace);
Console.WriteLine(result);

上面的代碼顯然對我不起作用,因為我們只替換匹配的文本。 如果我在上面的文本上運行代碼,我會得到“我的名字是 textEFG 而不是 textQWER”。 我需要的是“我的名字是文字而不是文字”。 我查看是否對所有單詞進行循環但試圖避免這種情況的唯一方法,看看我們是否有正則表達式方式。

您可以嘗試匹配模式\\bABCD\\w* ,它會匹配任何以ABCD開頭的單詞,但可能比這更長。

string input = "My name is ABCDEFG and not ABCDQWER";
string pattern = @"\bABCD\w*";
string replace = "text";
string result = Regex.Replace(input, pattern, replace);
Console.WriteLine(result);  // My name is text and not text

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM