【发布时间】:2019-04-06 23:25:26
【问题描述】:
我有一个字符串,我需要从中删除第一个连字符和下划线之间的数字。
字符串是:
string ProjectName1 = "1234-5678_abcd-efgh-(5000)|type";
string ProjectName2 = "0-4378_abcd-efgh-(5000)|type";
我试过了
Regex x = new Regex("(\\-\\)(.*?)(\\_\\)");
string repl = "";
string removeDigits = x.Replace(ProjectName, "$1" + repl + "$3");
结果应该是
ProjectName1="1234-abcd-efgh-(5000)|type";
ProjectName2="0-abcd-efgh-(5000)|type";
我已经尝试了上面的代码,但是得到了以下错误。
Error message: parsing "(\-\)(.*?)(\_\)" - Unrecognized escape sequence \_.
我用正则表达式尝试了不同的东西,但总是得到类似的错误。
任何帮助表示赞赏!
【问题讨论】:
-
Regex.Replace(input, @"(?<=^.*?)-\d+_", "-")将仅将"-"和"_"包围的第一个数字替换为"-" -
...而
Regex.Replace(input, @"(?<=^[^-]*)-\d+_", "-")会将"-"和"_"包围的数字替换为"-"仅如果它们出现在输入中的第一个"-"。