简体   繁体   中英

regex replacement word not working as expected

I have an incomplete xml file that needs a quick fix. Simplified, here is how it is coming in:

<positions><date></date><cust></cust><date></date><cust></cust></positions>

Here is what it needs to look like to process downstream:

</date><cust></cust></position><position><date></date><cust></cust></position></positions>

I thought this would work:

Regex r = new Regex(@"\b<date>\b");
findFirstTag = r.Replace(findFirstTag, "<position><date>");
Regex x = new Regex(@"\b</cust>\b");
findFirstTag = x.Replace(findFirstTag, "</cust></position>");

Console.WriteLine("Converted by regex: " + findFirstTag + "\n");

Nothing changed. Anyone?

You are using a word boundary , but there isn't one before the "<" or after the ">". A word boundary occurs on the change from a word character to a non word character or from a non word character to a word character. Here you want to have it between two non wordcharacters "><" this is always false.

Just remove it and you should be fine:

Regex r = new Regex(@"<date>");

and

Regex x = new Regex(@"</cust>");

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