atif
atif

Reputation: 1147

Using Regex to replace a specific string occurrence but ignore others based on neighboring characters

I have a string

   "sub section 15(1) of main section, this might be a <link href="15(1)">15(1)</link>". 

I want to use the Regex.Replace method to replace "15(1)" with a new string value of "15" but only where it occurs individually.

I am using the following pattern but it's not working.

 temp = "sub section 15(1) of main section, this might be a <link href="15(1)">15(1)</link>";    
 temp = Regex.Replace(temp, @"15(1)", @"15");

The output string should be:

"sub section 15 of main section, this might be a <link href="15(1)">15(1)</link>"

Any help will be appreciated.

Thanks

Upvotes: 2

Views: 1130

Answers (3)

user557597
user557597

Reputation:

This works (?<!\S)15\(1\)(?!\S)

Upvotes: 0

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

In your post you said you want to replace "15(1)" when it is "used individually." Does that mean when it is surrounded by whitespace?

This approach matches your desired output:

string pattern = @"(?<=^|\s)15\(1\)(?=\s|$)";
string result = Regex.Replace(input, pattern, "15");
Console.WriteLine(result);

This pattern will match only if the value occurs at the start of the line or is preceded by a whitespace character, and if it is followed by a whitespace character or the end of the line.

Upvotes: 1

Barry Kaye
Barry Kaye

Reputation: 7761

Try this (note you need to escape the brackets around 1):

\W15\(1\)\W

where \W is a non-word character; or

\s15\(1\)\s

where \s is a whitespace character.

Upvotes: 1

Related Questions