RegularExpression to replace extra space prefixed and suffixed with a particular character

Posted by SheoNarayan under Regular Expressions category on | Views : 3527
Below is the regular expression to replace extra space prefixed and siffixed with "|" (in this case) character, you can replace | with any character in below code snippet.

string s1 = "|  Sheo Narayan| Ram     Nagar|Shyam Nagar  |Gita Nagar";

// replace multiple space with single space first
s1 = Regex.Replace(s1, @"\s{2,}", " ");

// replace space suffixed with |
s1 = Regex.Replace(s1, @"\s[|]", "|");

// replace space prefixed with |
s1 = Regex.Replace(s1, @"[|]\s", "|");

Comments or Responses

Login to post response