簡體   English   中英

使用正則表達式僅匹配第 n 次出現

[英]Match only the nth occurrence using a regular expression

我有一個包含 3 個日期的字符串,如下所示:

XXXXX_20160207_20180208_XXXXXXX_20190408T160742_xxxxx

我想選擇字符串中的第二個日期,即20180208一個。

是否可以純粹在regex執行此操作,而必須求助於在代碼中提取 2 個匹配項。 如果這很重要,我正在使用C#

感謝您的幫助。

你可以用

^(?:[^_]+_){2}(\d+)

以第一組為例在 regex101.com 上查看演示


崩潰了,這說

var pattern = @"^(?:[^_]+_){2}(\d+)"; 
var text = "XXXXX_20160207_20180208_XXXXXXX_20190408T160742_xxxxx";
var result = Regex.Match(text, pattern)?.Groups[1].Value;
Console.WriteLine(result); // => 20180208

C# 演示

 var pattern = @"^(?:[^_]+_){2}(\\d+)"; var text = "XXXXX_20160207_20180208_XXXXXXX_20190408T160742_xxxxx"; var result = Regex.Match(text, pattern)?.Groups[1].Value; Console.WriteLine(result); // => 20180208

試試這個

MatchCollection 匹配 = Regex.Matches(sInputLine, @"\\d{8}");

字符串 sSecond = 匹配 [1].ToString();

你可以使用正則表達式

^(?:.*?\d{8}_){1}.*?(\d{8})

保存第二個日期以捕獲組 1。

演示

自然,對於n > 2 ,將{1}替換為{n-1}以獲得第 n日期。 為了獲得第1日起使用

^(?:.*?\d{8}_){0}.*?(\d{8})

演示

C# 的正則表達式引擎執行以下操作。

^        # match the beginning of a line
(?:      # begin a non-capture group
  .*?    # match 0+ chars lazily
  \d{8}  # match 8 digits
  _      # match '_'
)        # end non-capture group
{n}      # execute non-capture group n (n >= 0) times
.*?      # match 0+ chars lazily     
(\d{8})  # match 8 digits in capture group 1

需要注意的重要一點是.*? ,后跟\\d{8} ,因為它是懶惰的,將盡可能多地吞噬盡可能多的字符,直到接下來的 8 個字符是數字(並且前面或后面都沒有數字。例如,在字符串中

_1234abcd_efghi_123456789_12345678_ABC

(.*?)_\\d{8}_捕獲組 1 將包含"_1234abcd_efghi_123456789"

您可以使用System.Text.RegularExpressions.Regex

看下面的例子

Regex regex = new Regex(@"^(?:[^_]+_){2}(\d+)"); //Expression from Jan's answer just showing how to use C# to achieve your goal
GroupCollection groups = regex.Match("XXXXX_20160207_20180208_XXXXXXX_20190408T160742_xxxxx").Groups;
if (groups.Count > 1)
{
    Console.WriteLine(groups[1].Value);
}

暫無
暫無

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

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