简体   繁体   中英

RegEx for prefixed/unprefixed string

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" ?

Regex.Replace(before, "(<attr name=\"[first]?name\" />)", "$0<attr name=\"beep\" />");

Replacing the * with a ? will search for either one or zero occurences.

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\" />");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM