Choose exact match of digits from the string

I have input lines 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 use the regex below to select "001" in the TrackNumber group

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

However, the above also selects β€œ978”, β€œ133”, β€œ803”, etc. to the TrackNumber group (examples 1 and 2).

How to change the above expression to select only β€œ001” in TrackNumber?

-Alan -

+5
source share
1 answer

The following regular expression will match a 3-digit track number in all of 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 view that the next character is either a word boundary (i.e. a space) or an underscore

Demo

+3
source

Source: https://habr.com/ru/post/1245608/


All Articles