[英]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.replace或Regex.replace
string replace = Regex.Replace("a*", "([^a-zA-Z0-9])", "($1)");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.