简体   繁体   中英

Replace string using Regular expression

text = "The%20%20%20%20%20%20%20%20%20%20Park"
text = "The%20Park"

Even text has one %20 or multiple, it should have single char '-' eg The-Park

var regex = new Regex("%20(%20)?");
var output = regex.Replace("The%20%20%20%20%20%20%20%20%20%20Park", "-");
output = The----Park

but output should be The-Park

You are pretty close - use (%20)+ expression to match one or more occurrences of %20 :

var regex = new Regex("(%20)+");
var output = regex.Replace("The%20%20%20%20%20%20%20%20%20%20Park", "-");
Console.WriteLine(output);

Demo.

Good chances are, regex alone is not the right tool for the job. The string looks URL-encoded, with %20 representing spaces. You may be better off URL-decoding your string prior to applying a regex that looks for whitespace.

Your regex %20(%20)? matches a %20 and then 1 or 0 (an optional) %20 substring.

To match zero or more, you need to use * quantifier - %20(%20)* . However, this is equal to (%20)+ since + matches 1 or more occurrences of the quantified subpattern.

You can also use a non-regex approach with split and join.

See C# demo

var s = "The%20%20%20%20%20%20%20%20%20%20Park";
var regex = new Regex("(%20)+", RegexOptions.ExplicitCapture);
var output = regex.Replace(s, "-");
Console.WriteLine(output);           // => The-Park

output  = string.Join("-", s.Split(new[] {"%20"}, StringSplitOptions.RemoveEmptyEntries));
Console.WriteLine(output);           // => The-Park

Note that it is a good idea to use RegexOptions.ExplicitCapture if you do not want capturing groups (pairs of unescaped (...) ) in your pattern to create a stack for keeping captured values (just to steamline matching a bit).

I think you got your RegEx wrong.

The Regex.Replace() function is a greedy function that will always try to find the biggest string corresponding to your RegEx.

Your RegEx is %20(%20)? Which means "One occurrence of %20 plus zero or one occurrence of %20 " As you can see you find 4 of them in your string.

The RegEx you should be using is (%20)+ Which means "One or more occurrence of %20 "

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