Ahmad_Hamdan
Ahmad_Hamdan

Reputation: 87

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. 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

Answers (5)

walid toumi
walid toumi

Reputation: 2272

Try this pattern:

@c(?=1\D)1

Demo

Upvotes: 0

hwnd
hwnd

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

Avinash Raj
Avinash Raj

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();

IDEONE

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 30985

You can use this regex:

@c1\b

Working demo

enter image description here

The idea is to use a word boundary after your text and that would solve your problem

Upvotes: 5

vks
vks

Reputation: 67968

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

you can do this using negative lookahead

Upvotes: 1

Related Questions