Extract id from from image path

Viewed 92

I am looking to extract an id from a url/filepath

The path can be:

images/tJpwYL9baWgH56USKZwqTz7QM9g1_48x48.png or https://.../.../images/tJpwYL9baWgH56USKZwqTz7QM9g1_150x150.png

I would like to extract the unique ids (in this case tJpwYL9baWgH56USKZwqTz7QM9g1) So far I came up with the following expression: ([^\/]+[_$]) This includes however the _ , so I get tJpwYL9baWgH56USKZwqTz7QM9g1_

How can I do this and exclude the _?

1 Answers

You can use

([^\/]+)_\d+x\d+\.png
[^\/]+(?=_\d+x\d+\.png)

See this and this regex demo. Details:

  • ([^\/]+) - Capturing group 1: one or more chars other than /
  • _ - an underscore
  • \d+x\d+\.png - one or more digits, x, one or more digits, .png string
  • (?=_\d+x\d+\.png) - a positive lookahead that requires the pattern described above to appear immediately to the right of the current location (so, the text matched is not added to the match value)

Also, you might consider using simpler patterns like

([^\W_]+)_
[^\W_]+(?=_)

See this and this pattern demo. The [^\W_]+ pattern matches one or more letters or digits, (?=_) matches a location that is immediately followed with a _ char.

Related