简体   繁体   English

正则表达式匹配单词的开头但替换整个单词

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

I want to search for all words that start with a pattern and then replace the whole word with another text.我想搜索所有以模式开头的单词,然后用另一个文本替换整个单词。 I see that we can do a whole word match only and replace it but did not find a way of matching the start and replacing 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);

Above code obviously won't work for me because we are replacing only the text that matched.上面的代码显然对我不起作用,因为我们只替换匹配的文本。 If I run the code on the above text, I get "My name is textEFG and not textQWER".如果我在上面的文本上运行代码,我会得到“我的名字是 textEFG 而不是 textQWER”。 What I need is "My name is text and not text".我需要的是“我的名字是文字而不是文字”。 The only way I see if doing a loop on all the words but trying to avoid that and see if we have a regex way.我查看是否对所有单词进行循环但试图避免这种情况的唯一方法,看看我们是否有正则表达式方式。

You may try matching on the pattern \\bABCD\\w* , which would match any word which starts with ABCD , which however may be longer than that.您可以尝试匹配模式\\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