Alan B
Alan B

Reputation: 2289

Pick the exact digit match from a string

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-

Upvotes: 5

Views: 83

Answers (1)

Keith Hall
Keith Hall

Reputation: 16075

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

Upvotes: 3

Related Questions