[英]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: 除了Marc的
"($1)"
答案之外,您还可以使用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. 当您需要对找到的模式进行更复杂的操作时,这将主要有用。
replacng single chars and not the '.' 替换单个字符而不是“。” :
:
Regex.Replace(test, @"[^a-zA-z0-9\. ]", m => "(" + m.Value + ")");
您可以使用string.replace或Regex.replace
string replace = Regex.Replace("a*", "([^a-zA-Z0-9])", "($1)");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.