开发者

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


you can use string.replace or Regex.replace

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜