输入应该是这样的:
123 - string I want - with dash included
或
123 - string I want
或
string I want - with dash included
或
string I want
什么是正则表达式string I want - with dash included
或string I want
,我希望删除前导数字部分“123 - ”如果输入以数字开头,则不删除其他数字。
答案 0 :(得分:2)
您可以使用以下内容。
string input = "123 - string I want - with dash included";
string output = Regex.Replace(input, @"^\d+\W+", "");
// => "string I want - with dash included"
正则表达式
^ # the beginning of the string
\d+ # digits (0-9) (1 or more times)
\W+ # non-word characters (all but a-z, A-Z, 0-9, _) (1 or more times)
另一种选择是使用可选的分组和捕获组并进行替换。
string input = "123 - string I want - with dash included";
string output = Regex.Replace(input, @"^(\d+\W+)?(.*)$", "$2");
// => "string I want - with dash included"