Take the 2-minute tour ×

I've a string and I'm using a RegEx for replacing the string to a specific pattern. Basically I want to trim the white spaces within the named group

For Eg:

myString1: substringof('test',Name)
myString2: substringof(' test ',Name)
myString3: substringof('test ',Name)

Expected output: Name.Contains(\"test\")

myString4: substringof(' test test ',Name)
myString5: substringof(' test test',Name)
myString6: substringof('test test ',Name)  

Expected output: Name.Contains(\"test test\")


var replaceRegex = new Regex(substringof\\(\\s*'(?<text>[^']+'?[^']*)'\\s*,\\s*(?<pname>[\\w\\[\\]]+)\\s*\\)");
myString = replaceRegex.Replace(myString, "${pname}.Contains(\"${text}\")");

Any help will be appreciated. Thanks in advance!!

share|improve this question
why regex and not trim? –  Sayse Jun 3 '13 at 21:39
add comment

1 Answer

Use string.Trim, but if you insist on Regex:


That says not space, then a "word" which can be space separated, then not space.

Another fun way to avoid Regex, and if you want to trim the space BETWEEN words, would be to use string split and join:

var text = " name name "; // sample
var result = string.Join(" ", text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
share|improve this answer
Or just use (?<=^\s*)\S.*?(?=\s*$). The match will be the trimmed string. –  JDB Jun 3 '13 at 21:50
Also good. I prefer to avoid look ahead/behind when I can, but both work. –  Haney Jun 3 '13 at 21:51
string.Trim would almost certainly be correct. Any other solution is needlessly complex. –  JDB Jun 3 '13 at 21:51
Exactly why I didn't even look into a solution @Cyborgx37 :P (+1 for both answers though DavidH) –  Sayse Jun 3 '13 at 21:53
But needlessly complex approaches are the spice of life, @Sayse! –  JDB Jun 4 '13 at 3:12
show 1 more comment

Your Answer


