podeig
podeig

Reputation: 2741

Need to fix a regex, which replaces too much

I have such string:

Text [City 1 || Location] text [Population] 
|| Text [City 2 || Location] text [Population]

I need regex which replace || just within [] with ==.

So i must be:

Text [City 1 == Location] text [Population] 
|| Text [City 2 == Location] text [Population]

I wrote this regex:

str = Regex.Replace(str, @"\[(.*?)\|\|(.*?)\]", "[$1==$2]");

But it replaces all || with ==.

How to fix it?

Upvotes: 1

Views: 99

Answers (2)

davidrac
davidrac

Reputation: 10738

You should be able to avoid matching everything and only get the '||' like that:

str = Regex.Replace(str, @"(?<=\[[^\[\]]*)\|\|(?=[^\[\]]*\])", "==");

So what is happening here?

(?<=\[[^\[\]]*) this is a zero width look behind that matches '[' and any character following it, other than '[' or ']'

\|\| this matches the actual '||'

(?=[^\[\]]*\]) this is a zero width look ahead that matches any character other than '[' or ']', followed by ']'

Upvotes: 1

Ria
Ria

Reputation: 10347

EDIT: Try using lookbehind and lookahead assertions:

(?<= subexpression)
Zero-width positive lookbehind assertion.  

(?= subexpression)
Zero-width positive lookahead assertion. 

Upvotes: 1

Related Questions