簡體   English   中英

正則表達式提取數字的第一個實例並替換C#中的其他所有內容

[英]Regex to extract first instance of number and replace everything else in C#

我有一個看起來像這樣的字符串:

/ some / example / path / here / [somePositiveInteger] _.000

其中[somePositiveInteger]是一些正整數(例如1,23542,331232等), _.000可以是_.101_.343 . _.343等。

我想改變它看起來像:

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

我想我可以通過在/上拆分字符串來提取[somePositiveNumber] ,然后刪除_.000 ,然后將數字追加到/some/example/path/here/dispform.aspx?id=

然而,這看起來像正則表達式可以更有效地做。 我如何使用正則表達式執行此操作?

試試這個例子:

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;
}

請注意,它使用正則表達式來匹配模式,然后從結果匹配中構造一個新字符串。 如果輸入不是必需的形式,它會拋出異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM