0

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Lucas Andrade
  • 4,315
  • 5
  • 29
  • 50

2 Answers2

1

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);
felixmosh
  • 32,615
  • 9
  • 69
  • 88
1

\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

revo
  • 47,783
  • 14
  • 74
  • 117