[英]Replacing a String with Regular expression
假设我有一个类似“ Hello @ c1,请到这里玩@ c12,@ c1去玩”的文本,我想编写一个模式,用一些值替换所有@ c1,但同时正则表达式不得更改@ c12或@ c123等。它应仅替换匹配的字符串。 我已经尝试了几个小时,但未能产生正确的输出,因此任何人都可以通过文章或代码示例帮助我解决该问题
我正在使用.Net Framework编写正则表达式
您可以在此处使用单词边界\\b
或否定超前 。
单词边界断言,一侧有一个单词字符,而另一侧则没有。
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"
否定的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])
您可以使用负前瞻进行此操作
您可以使用先行搜索和后退搜索,
(?<=\W|^)@c1(?=\W|$)
码:
string str = "Hello @c1, please go here and play with @c12, @c1 goes and plays";
string result = Regex.Replace(str, @"(?<=\W|^)@c1(?=\W|$)", "foo");
Console.WriteLine(result);
Console.ReadLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.