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
CodePudding user response:
You may use this regex with an optional group:
^Log-(?<timestamp>\d (?:_\d{4,})?)(?:_(?<sequence>\d{3}))?\.txt
RegEx Details:
^
: StartLog-
: MatchLog-
(?<timestamp>\d _(?:_\d{4,})?)
: Match and capturedigits_digits
in names grouptimestamp
where part after_
is optional.(?:_(?<sequence>\d{3}))?
: Optional group that starts with_
and matched and captures 3 digits in named groupsequence
\.txt
: Match.txt