Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick the exact digit match from a string

Tags:

c#

regex

I have the input strings as below

1) ISBN_9781338034424_001_S_r1.mp3

2) 001_Ch001_987373737.mp3

3) This Is test 001 Chap01.mp3

4) Anger_Cha01_001.mp3

and I am using below regex to pick "001" into TrackNumber group

(?:(?<TrackNumber>\d{3})|(?<Revision>r\d{1}))(?![a-zA-Z])

However the above also picking up the "978", "133", "803" and etc into TrackNumber group (example 1 and 2) .

How do I change the above regex to pick only the "001" into TrackNumber?

-Alan-

like image 295
Alan B Avatar asked Oct 19 '22 13:10

Alan B


1 Answers

The following regular expression will match the 3 digit track number in all your examples:

(?<=\b|_)(?<TrackNumber>\d{3})(?=\b|_)
  • (?<=\b|_) positive lookbehind, that the previous character is either a word boundary (i.e. a space) or an underscore
  • (?=\b|_) positive lookahead, that the next character is either a word boundary (i.e. a space) or an underscore

Demo

like image 196
Keith Hall Avatar answered Oct 21 '22 03:10

Keith Hall