简体   繁体   English

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

[英]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. 当您需要对找到的模式进行更复杂的操作时,这将主要有用。

Edit: 编辑:

replacng single chars and not the '.' 替换单个字符而不是“。” :

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.

相关问题 拒绝非字母数字字符的正则表达式 - regular expression to reject non-alphanumeric characters 仅从字符串的开头和结尾删除非字母数字字符 - Remove non-alphanumeric characters from start and end of string only .NET正则表达式,用于检查长度和非字母数字字符 - .NET Regular expression which check length and non-alphanumeric characters 正则表达式-过滤字母和非字母数字字符 - Regular Expressions - Filtering alphabetic and non-alphanumeric characters 正则表达式,允许用户输入字母数字字符和仅一个非字母数字字符 - Regular expression for allowing a user to enter alphanumeric characters and only one non-alphanumeric character 如何使用正则表达式从输入字符串中提取所有非字母数字字符? - How can I extract all non-alphanumeric characters from an input string using Regular Expressions? 如何从字符串中去除非字母数字字符(包括空格)? - How do I strip non-alphanumeric characters (including spaces) from a string? 字符串包含非字母数字字符(如中文或日语)时的对齐问题 - Alignment issue when string contains non-alphanumeric characters like Chinese or Japanese RC4加密非字母数字错误 - RC4 Encryption non-alphanumeric wrong 连接字符串中的非字母数字(例如分号) - non-alphanumeric (ex semicolon) in connectionstring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM