sagivasan sagivasan - 1 year ago 93
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
or multiple, it should have single char

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

Thanks in advance

Answer Source

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", "-");


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download