Evolving Techie
Evolving Techie

Reputation: 159

How to trim white space within Regex using c#

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\")

CODE:

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!!

Upvotes: 1

Views: 3123

Answers (1)

Haney
Haney

Reputation: 34762

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

[^\s.*](?<pname>\w.*)[^\s.*]

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

Upvotes: 6

Related Questions