Malfist
Malfist

Reputation: 31795

C#'s regex not working like I want it too

I have an input string like this:

\pard\nowidctlpar\qj\b0\scaps This Agreement\scaps0 is made and entered into this date, \{#DATEAGREEMENT#\} , by and between [removed] (\ldblquote [removed]\rdblquote ), and its successors and/or assigns, with address at [removed], and \{#TXTPLAINTIFF#\} , (\ldblquote Plaintiff\rdblquote ), Individually, of ___________________, and, \{#TXTPLAINTIFFATTORNEY#\} , (\ldblquote Plaintiff\rquote s Attorney\rdblquote ) of \{#TXTATTORNEYFIRM#\} .\par

and I want to do some parsing with regex.

This is the code I'm using:

temp = Regex.Replace(temp, @"\\{#.*#\\}", "_____");

The only problem is it matches the widest set, i.e. it takes out the whole paragraph because the paragraph ends with "#\}", how can I get to match each group? I.E., this paragraph should match it 4 times instead of once.

Upvotes: 1

Views: 288

Answers (4)

Patrick
Patrick

Reputation: 8318

You're looking for lazy evaluation:

temp = Regex.Replace(temp, @"\\{#.*?#\\}", "_____");

may do it

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95518

Did you try making it a non-greedy match?

temp = Regex.Replace(temp, @"\\{#.*?#\\}", "_____");

Upvotes: 4

Powerlord
Powerlord

Reputation: 88796

As I recall, adding a ? changes an operator from greedy to non-greedy, so try this:

temp = Regex.Replace(temp, @"\\{#.*?#\\}", "_____");

Upvotes: 1

Dan McClain
Dan McClain

Reputation: 11920

temp = Regex.Replace(temp, @"\\{#.*?#\\}", "_____");

Appending a '?' to the '*' will perform a un-greedy search. Your initial regex was performing a greedy search, so it would look for the largest possible match.

Upvotes: 1

Related Questions