user12324017
user12324017

Reputation: 29

How to match filename words without the extension using regex?

I want to match the words in a filename without characters like underscores (_) and the file extension. For example, if i have the files image_one.jpg and image_two.png then how can I match only image one and image two? I am not sure how to exclude the underscore and the .extension.

So far, I have \w*_\w* but it matches the file name including the underscore i.e. image_one and image_two

Upvotes: 1

Views: 906

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

Your pattern \w*_\w* could possibly also match a single _ as the word chars are optional.

As \w also matches an underscore, you can exclude it from \w by using a negated character class.[^\W_].

To get both values, you could use 2 capturing groups and if the pattern must only match at the end of the string you can add $ at the end.

([^\W_]+)_([^\W_]+)\.\w+

Explanation

  • ([^\W_]+) Capture group 1, match 1+ times a word char except _
  • _ Match the underscore
  • ([^\W_]+) Capture group 2, same as for group 1
  • \.\w+ Match a . and 1+ word chars (or \.(?:jpg|png) to be more precise)

See a Regex demo

const regex = /([^\W_]+)_([^\W_]+)\.\w+/;
[
  "image_one.jpg",
  "image_two.png"
].forEach(s => console.log(s.match(regex).slice(1)));

Upvotes: 1

Related Questions