Search code examples
javascriptregexoption-typeregex-groupoptional-values

How to make a optional group, but if the group exists most match with my regex?


I have this JS regex:

var re = /(\w\w\d-{1})?\w\w-{1}\w-{1}?/;

For file name, and the first group must be optional:

Complete name example. Example:

qq8-qq-q-anything => OK

Without first group:

qq-q-anything => OK

But if I put anything, still worked:

anything-qq-q-anything => OK

I want the first group to be optinal, but if the file name has the first group it must match with my regex word wor digit.


Solution

  • You should specify that the string should "start with" your regex, so only add ^ to specify the start point.

    const re = /^(\w\w\d-{1})?\w\w-{1}\w-{1}?/;
    
    const strs = ['qq8-qq-q-anything', 'qq-q-anything', 'anything-qq-q-anything'];
    
    
    const result = strs.map(str => re.test(str));
    
    console.log(result);