1
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

3
  • 2
    "%20(%20)?" -> "%20(%20)*" -> "(%20)+" Commented Aug 18, 2016 at 11:32
  • @WiktorStribiżew, thanks its worked fine. Commented Aug 18, 2016 at 11:36
  • I added an answer with explanations and an alternative non-regex solution. Commented Aug 18, 2016 at 11:45

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks and its my first regex build. Its URL-encoded. i need to - instead of space so that i used regex.
@sagivasan I would decode, replace, and re-encode just to be safe.
2

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).

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.