用正则表达式替换字符串

时间:2014-09-09 17:40:01

标签: c# regex text

假设我有一个像“Hello @ c1,请到这里玩@ c12,@ c1去玩和播放”这样的文字,我想写一个模式来取代所有@ c1的某些值,但在同时正则表达式不能改变@ c12或@ c123等。 它应该只替换匹配的字符串。我已经尝试了几个小时,但未能产生正确的输出,所以任何人都可以通过文章或代码示例帮助我做些什么

我正在使用.Net Framework来编写正则表达式

5 个答案:

答案 0 :(得分:5)

您可以使用此正则表达式:

@c1\b

<强> Working demo

enter image description here

这个想法是在你的文字之后使用一个单词边界,这将解决你的问题

答案 1 :(得分:2)

您可以在此处使用字边界\bNegative Lookahead

一个单词边界断言,一方面有一个单词字符,另一方面则没有。

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断言在字符串中的那个位置,紧随其后的不是数字。

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"

答案 2 :(得分:1)

@c1(?![a-zA-Z0-9])

你可以使用负向前瞻

来做到这一点

答案 3 :(得分:0)

你可以使用前瞻和后视,

(?<=\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();

IDEONE

答案 4 :(得分:0)

尝试这种模式:

@c(?=1\D)1

Demo

相关问题