C# 正则表达式提取数字的第一个实例并替换C中的所有其他内容#

C# 正则表达式提取数字的第一个实例并替换C中的所有其他内容#,c#,regex,C#,Regex,我有一个字符串,看起来像: /some/example/path/here/[somePositiveInteger]\uuu.000 其中,[somePositiveInteger]是某个正整数(例如123542、331323等),.000可以是\u101,\u343等 我想将此更改为类似以下内容: /some/example/path/here/dispform.aspx?id=[somePositiveInteger] 我想我可以通过拆分/上的字符串来提取[somepositiveEnum

我有一个字符串,看起来像:

/some/example/path/here/[somePositiveInteger]\uuu.000

其中,[somePositiveInteger]是某个正整数(例如123542、331323等),
.000
可以是
\u101
\u343

我想将此更改为类似以下内容:

/some/example/path/here/dispform.aspx?id=[somePositiveInteger]

我想我可以通过拆分
/
上的字符串来提取[somepositiveEnumber],然后删除
.000
,然后将数字追加回
/some/example/path/here/dispform.aspx?id=

然而,这似乎是正则表达式可以更有效地完成的事情。那么,如何使用regex实现这一点呢?

尝试以下示例:

string input = "/some/example/path/here/99999_.000";
input = Regex.Replace(input, @"(.*/)(\d+)_\.\d{3}$", "$1"+"dispform.aspx?id=$2");
$1
保存正则表达式
(.*/)


$2
保存正则表达式所需的数字
(\d+)

以下方法生成您描述的结果:

static string ConvertPath(string input)
{
    var match = Regex.Match(input, @"^(.*)/(\d+)_\.\d\d\d$");
    if (!match.Success)
        throw new ArgumentException("The input does not match the required pattern.");
    return match.Groups[1].Value + "/dispform.aspx?id=" + match.Groups[2].Value;
}

请注意,它使用正则表达式匹配模式,然后根据结果匹配构造新字符串。如果输入的格式不是必需的,则会引发异常。

这两种解决方案对我都有效,因此我必须将其交给在这种情况下首先回答的人(:感谢您和@Timwi)