Skip to main content
 首页 » 编程设计

C# 正则表达式 : replace either of two matches with the same value

2024年01月25日26lovecherry

尝试在字符串中进行一些正则表达式匹配和替换,从而将所有与号、单引号和空格字符替换为破折号“-”

...和

所有重复的破折号都被替换为一个破折号。

这就是我正在尝试的方法,但它不起作用,因为重复的破折号没有被替换。感谢任何帮助。

Regex.Replace(mystring, "([' &])|([-]{2,})", "-") 

请您参考如下方法:

试试这个(看起来更简单)。我假设您永远不想在结果中使用“--”。

string orig = "12467&89- 1&2467'89 12'46789 12467--89"; 
 
Regex regex = new Regex("[&' -]+"); 
 
string newString = regex.Replace(orig, "-"); 

输出:

12467-89-1-2467-89-12-46789-12467-8