替换C#字符串中的多个字符 [英] Replace multiple characters in a C# string
问题描述
是否有更好的替换字符串的方法?
Is there a better way to replace strings?
令我惊讶的是,Replace没有包含字符数组或字符串数组。我想我可以编写自己的扩展名,但我很好奇是否有更好的内置方法可以执行以下操作?请注意,最后一个Replace是字符串而不是字符。
I am surprised that Replace does not take in a character array or string array. I guess that I could write my own extension but I was curious if there is a better built in way to do the following? Notice the last Replace is a string not a character.
myString.Replace(';', '\n').Replace(',', '\n').Replace('\r', '\n').Replace('\t', '\n').Replace(' ', '\n').Replace("\n\n", "\n");
推荐答案
您可以使用替换正则表达式。
You can use a replace regular expression.
s/[;,\t\r ]|[\n]{2}/\n/g
-
s /
开头表示搜索 -
[
和]
之间的字符是要搜索的字符(以任何顺序) - 第二个
/
分隔搜索文本和替换文本 s/
at the beginning means a search- The characters between
[
and]
are the characters to search for (in any order) - The second
/
delimits the search-for text and the replace text
在英语中为:
搜索;
或,
或 \t
或 \r
或
(空格)或正好两个连续的 \n
并将其替换为 \n
"Search for ;
or ,
or \t
or \r
or (space) or exactly two sequential
\n
and replace it with \n
"
在C#中,您可以执行以下操作:(在导入 System.Text之后.RegularExpressions
)
In C#, you could do the following: (after importing System.Text.RegularExpressions
)
Regex pattern = new Regex("[;,\t\r ]|[\n]{2}");
pattern.Replace(myString, "\n");
这篇关于替换C#字符串中的多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!