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

491 Views Asked by At

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.

2

There are 2 best solutions below

0
felixmosh On BEST ANSWER

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);

0
revo On

\w matches both digits and letters. It includes _ character too. You should explicitly use a character class for letters and anchor your regex with circumflex ^ to assert start of input string. You don't need to have {1} quantifier either since a preceding pattern is only checked once unless defined otherwise. You may need i (case-insensitive) flag too:

var re = /^(?:[a-z]{2}\d-)?[a-z]{2}-[a-z]-/i;

Live demo