简体   繁体   English

用正则表达式替换字符串

[英]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

Working demo 工作演示

在此处输入图片说明

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])

您可以使用负前瞻进行此操作

You could use a lookahead and lookbehind, 您可以使用先行搜索和后退搜索,

(?<=\W|^)@c1(?=\W|$)

Code: 码:

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 爱迪生

Try this pattern: 试试这个模式:

@c(?=1\D)1

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM