Home > OS >  Regex: match patterns starting from the end of string
Regex: match patterns starting from the end of string

Time:10-29

I wish to match a filename with column and line info, eg.

\path1\path2\a_file.ts:17:9

//what i want to achieve:
match[1]: a_file.ts
match[2]: 17
match[3]: 9

This string can have garbage before and after the pattern, like

(at somewhere: \path1\path2\a_file.ts:17:9 something)

What I have now is this regex, which manages to match column and line, but I got stuck on filename capturing part.. I guess negative lookahead is the way to go, but it seems to match all previous groups and garbage text in the end of string.

(?!.*[\/\\]):(\d ):(\d )\D*$

Here's a link to current implementation regex101

CodePudding user response:

You can replace the lookahead with a negated character class:

([^\/\\] ):(\d ):(\d )\D*$

See the regex demo. Details:

  • ([^\/\\] ) - Group 1: one or more chars other than / and \
  • : - a colon
  • (\d ) - Group 2: one or more digits
  • : - a colon
  • (\d ) - Group 3: one or more digits
  • \D*$ - zero or more non-digit chars till end of string.
  • Related