替换文本中的非字母数字字符

时间:2011-09-24 09:25:27

标签: c# regex

我想在括号内加上文本中的非字母数字字符。

例如:

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

我想通过正则表达式方法在括号内放置上面字符串中的非字母数字字符。

结果:

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

3 个答案:

答案 0 :(得分:4)

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

或更具选择性:

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

答案 1 :(得分:1)

另外,对于Marc的"($1)"答案,您还可以使用MatchEvaluator:

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

当您需要对找到的模式进行更复杂的操作时,这将非常有用。

编辑:

更换单个字符而不是'。' :

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

答案 2 :(得分:0)

您可以使用string.replaceRegex.replace

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