1

I'm trying to match the following file formats to prefix the files with an absolute URL. The strings are part of an index.html file and I'm using npm replace to find/replace. Here are the different file names:

  • favicon.ico
  • main.somestringwithcharacterandletters.css
  • main.somestringwithcharacterandletters.js
  • somestringwithcharactersandletters.woff
  • somestringwithcharactersandletter.ttf

I've tried the following regex:

(main\.)?(\w)+\.(css|js|woff|woff2|eot|ttf|png|ico){1}

This matches the last character in the filename and the extension instead of the full filename and the extension. What needs to be changed to match the full filename so I can prefix an absolute path?

6
  • 1
    Note that {1} is never ever useful in regex. A quantifier of 1 occurrence is the same as no quantifier Commented Jul 26, 2016 at 15:07
  • 1
    Add another set of brackets? Commented Jul 26, 2016 at 15:07
  • 3
    (\w)+ -> (\w+). Instead of quantifying a group that captures the last matched value, you should quantify the pattern inside the group. Commented Jul 26, 2016 at 15:10
  • Add a $ at the end to indicate that it should match the end part of the name no matter what intervening folders are called? Commented Jul 26, 2016 at 15:10
  • Not my issue. As you see from that regex101 it is working for me. I haven't tried it with npm replace. I can see your suggestion is more logical. Commented Jul 26, 2016 at 17:16

1 Answer 1

1

Remove the redundant {1} and what is more important - move the + into the second capture group:

(main\.)?(\w+)\.(css|js|woff2?|eot|ttf|png|ico)
            ^                                  ^

See the regex demo.

enter image description here

When you set a quantifier to a group, the whole group pattern is matches repeatedly, but the contents of the group stack is constantly re-written with each subsequent match. Thus, always check what you quantify, in many situations, you want to quantify the group pattern, not the group itself (unless it is a non-capturing group, when you know nothing is captured and we use it to just group a sequence of subpatterns).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.