Reputation: 87
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. 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
Upvotes: 1
Views: 107
Reputation: 70722
You can either use a word boundary \b
or Negative Lookahead here.
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.
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"
Upvotes: 2
Reputation: 174696
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();
Upvotes: 0
Reputation: 30985
You can use this regex:
@c1\b
The idea is to use a word boundary after your text and that would solve your problem
Upvotes: 5