繁体   English   中英

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

[英]replacing non-alphanumeric characters within a text

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

例如:

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

我想通过正则表达式方法将括号内的非字母数字字符放在括号内。

结果:

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

或者更具选择性:

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

除了Marc的"($1)"答案之外,您还可以使用MatchEvaluator:

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

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

编辑:

替换单个字符而不是“。”

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

您可以使用string.replaceRegex.replace

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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