Benny Mose
Benny Mose

Reputation: 755

Matching part before and after underscore of filename

I'm trying to match parts before and after an underscore _ in these filenames, but also the file without the underscore, e.g.:

test.jpg
test_1.jpg
test_2.jpg

I can match parts before and after using: ^(\w+)_(\d+).*$ - but this does not match test.jpg.

How do I approach this?

Upvotes: 2

Views: 83

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

Make the _ optional using ? quantifier

^(\w+)(?:_(\d+))?.*$

Regex Demo

Changes made

  • (?:_(\d+))? The quantifier ? matches zero or one occurence of the previous regex

Upvotes: 6

Related Questions