简体   繁体   中英

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(*)."
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)");

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

您可以使用string.replaceRegex.replace

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM