MaxCoder88
MaxCoder88

Reputation: 2428

replacing non-alphanumeric characters within a text

I want to put inside parentheses the non-alphanumeric characters within a text.

For example:

"I would like to add * parentheses % around certain text within cells*."

I want to put inside parentheses via regex method the non-alphanumeric characters within above string.

Result:

"I would like to add (*) parentheses (%) around certain text within cells(*)."

Upvotes: 1

Views: 1481

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273244

In additio to Marc's "($1)" answer, you can also use a MatchEvaluator:

Regex.Replace(test, "[^a-zA-z0-9 ]+", m => "(" + m.Value + ")");

Which would mainly be useful when you need to do more complicated manipulation of the found patterns.

Edit:

replacng single chars and not the '.' :

Regex.Replace(test, @"[^a-zA-z0-9\. ]", m => "(" + m.Value + ")");

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062770

string s = Regex.Replace(
    @"I would like to add * parentheses % around certain text within cells*.",
    @"([^.\d\w\s])", "($1)");

or to be more selective:

string s = Regex.Replace(
    @"I would like to add * parentheses % around certain text within cells*.",
    @"([*%])", "($1)");

Upvotes: 4

meziantou
meziantou

Reputation: 21337

you can use string.replace or Regex.replace

string replace = Regex.Replace("a*", "([^a-zA-Z0-9])", "($1)");

Upvotes: 0

Related Questions