简体   繁体   中英

C# Regex remove ampersand

I have the following string: {}&{} and I want to remove ampersand to get {}{}. Here is my Regex.Replace call:

Regex.Replace(@"\{\}&\{\}", @"\}.&\{", "}{")

I have no idea why it doesn't work.

Why complicating? why not just:

myString.Replace("}&{", "}{"); // replaces '}&{' with '}{'

What's the . doing there? That's going to match against any character, and since there is nothing between } and & it will fail to match. Try remove it:

Regex.Replace(@"\{\}&\{\}", @"\}&\{", "}{")

See it on rubular

Or make the character optional with ? :

Regex.Replace(@"\{\}&\{\}", @"\}.?&\{", "}{")

See it on rubular

If you are not sure there is something between the ampersand and the curly bracket, but there could be something, add an asterisk after the period:

Regex.Replace(@"\{\}&\{\}", @"\}.*&\{", "}{")
/*                              ^^ here  */

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