leon
leon

Reputation: 433

Regex: backtracking and optional quantifier

I have some file names and I want to get the timestamp and optional sequence number out of it.

Log-20220408_212412_001.txt           
Log-20220408_212412.txt    
Log-20220408_2124.txt

I used

Log-(?<timestamp>[0-9_]+)(?<sequence>_[\d]{3})?.txt$

In C#, it works if I configure regex to search from "right to left". But the "right to left" flag is not commonly supported. Is there any alternative way to do it? Thanks

Upvotes: 1

Views: 60

Answers (1)

anubhava
anubhava

Reputation: 784868

You may use this regex with an optional group:

^Log-(?<timestamp>\d+(?:_\d{4,})?)(?:_(?<sequence>\d{3}))?\.txt

C# RegEx Demo

RegEx Details:

  • ^: Start
  • Log-: Match Log-
  • (?<timestamp>\d+_(?:_\d{4,})?): Match and capture digits_digits in names group timestamp where part after _ is optional.
  • (?:_(?<sequence>\d{3}))?: Optional group that starts with _ and matched and captures 3 digits in named group sequence
  • \.txt: Match .txt

Upvotes: 1

Related Questions