sagivasan sagivasan - 3 months ago 10
C# Question

Replace string using Regular experssion

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


Thanks in advance

Answer

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.