Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to replace string except in sqaure brackets

Tags:

c#

regex

Need to replace all forward-slash (/) with > except for the ones in the square brackets

input string:

string str = "//div[1]/li/a[@href='https://www.facebook.com/']";

Tried pattern (did not work):

string regex = @"\/(?=$|[^]]+\||\[[^]]+\]\/)";
var pattern = Regex.Replace(str, regex, ">");

Expected Result:

">>div[1]>li>a[@href='https://www.facebook.com/']"
like image 633
Sandeep Dhamale Avatar asked Mar 04 '26 19:03

Sandeep Dhamale


1 Answers

Your thinking was good with lookbehind but instead positive use negative.

(?<!\[[^\]]*)(\/)

Demo

After updating your c# code

string pattern = @"(?<!\[[^\]]*)(\/)";
string input = "//div[1]/li/a[@href='https://www.facebook.com/']";
var result = Regex.Replace(input, pattern, ">");

You will get

>>div[1]>li>a[@href='https://www.facebook.com/']
like image 85
Pietro Avatar answered Mar 07 '26 08:03

Pietro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!