Reputation:
I'm trying to perform a conversion on my XML string by detecting a tag that's always like this:
<attr name="firstName" />
<attr name="Name" />
<attr name="lastName" />
I wish to catch it and replace it by itself with a suffix so I'll get this:
<attr name="firstName" /><attr name="beep" />
<attr name="Name" /><attr name="beep" />
But if it's the last one, I wish not to do anything at all.
<attr name="lastName" />
I'm trying with this detection pattern.
Regex.Replace(before, "(<attr name=\"[first]*name\" />)", "[0]<attr name=\"beep\" />");
But this will match all permutations of first. How can I express at most one of the exact string "first"?
Upvotes: 0
Views: 75
Reputation: 239764
I think what you want is:
Regex.Replace(before, "(<attr name=\"(?:first)?name\" />)", "$0<attr name=\"beep\" />");
[first]
in a regular expression says "any of the characters f
, i
, r
, s
or t
".
(?:first)
says "the string of characters first
, treated as a (non-capturing) group". ?
then says that the preceeding match should occur zero or one time.
Upvotes: 0
Reputation: 3039
I suggest using a negative lookahead:
Regex.Replace(before, "(<attr name=\"(?!last)[^\"]*Name\" />)", "$0<attr name=\"beep\" />");
To detect zero or one of the string "first", then you can simply change the lookbehind into a normal group that is optional, and replace "last" with "first".
Regex.Replace(before, "(<attr name=\"(?:first)?Name\" />)", "$0<attr name=\"beep\" />");
Upvotes: 1
Reputation: 5312
Regex.Replace(before, "(<attr name=\"[first]?name\" />)", "$0<attr name=\"beep\" />");
Replacing the *
with a ?
will search for either one or zero occurences.
Upvotes: 1