开发者

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:

"开发者_如何学Gosub section 15 of main section, this might be a <link href="15(1)">15(1)</link>"

Any help will be appreciated.

Thanks


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜