[英]Replacing a String with Regular expression
Suppose that I have a text like "Hello @c1, please go here and play with @c12, @c1 goes and plays", I would like to write a pattern to replace all of @c1 with some value but in the same time the regular expression must not change @c12 or @c123 etc.. it should replace only the matched string. 假设我有一个类似“ Hello @ c1,请到这里玩@ c12,@ c1去玩”的文本,我想编写一个模式,用一些值替换所有@ c1,但同时正则表达式不得更改@ c12或@ c123等。它应仅替换匹配的字符串。 I have been trying for hours, but failing to produce the right output, so can anyone can help me with what to do regarding it with articles or code samples
我已经尝试了几个小时,但未能产生正确的输出,因此任何人都可以通过文章或代码示例帮助我解决该问题
I am using .Net Framework for writing the Regular expression 我正在使用.Net Framework编写正则表达式
You can use this regex: 您可以使用此正则表达式:
@c1\b
The idea is to use a word boundary after your text and that would solve your problem 想法是在文本后使用单词边界,这将解决您的问题
You can either use a word boundary \\b
or Negative Lookahead here. 您可以在此处使用单词边界
\\b
或否定超前 。
A word boundary asserts that on one side there is a word character, and on the other side there is not. 单词边界断言,一侧有一个单词字符,而另一侧则没有。
String s = "Hello @c1, please go play with @c12 and @c123";
String r = Regex.Replace(s, @"@c1\b", "foo");
Console.WriteLine(r); //=> "Hello foo, please go play with @c12 and @c123"
Negative Lookahead asserts that at that position in the string, what immediately follows is not a digit. 否定的Lookahead断言,在字符串中的该位置处,紧随其后的不是数字。
String s = "Hello @c1, please go play with @c12 and @c123";
String r = Regex.Replace(s, @"@c1(?!\d)", "foo");
Console.WriteLine(r); //=> "Hello foo, please go play with @c12 and @c123"
@c1(?![a-zA-Z0-9])
您可以使用负前瞻进行此操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.