Home > Software engineering >  Matching same start with different end
Matching same start with different end

Time:08-11

Javascript engine. Two possible format are accepted

12-1-12

123

My attempt:

\d{2}(-\d-\d{2})|(\d)

which matches the first case

enter image description here

but not the second one

enter image description here

CodePudding user response:

| has the lowest priority. Your expression means \d{2}-\d-\d{2} or \d. You need to wrap the fragment that uses | into parentheses:

\d{2}((-\d-\d{2})|(\d))

The inner parentheses are useless now:

\d{2}(-\d-\d{2}|\d)

A more readable way, in my opinion, is to create a separate regex for your cases and join them by |:

\d{2}-\d-\d{2}|\d{3}

The first part (\d{2}-\d-\d{2}) matches 12-1-12, the second part (\d{3}) matches 123. The entire expression matches both (the first or the second).

All these regexps match the mentioned strings even when they are substrings of larger strings. If you need to match exactly 12-1-12 and not 4412-1-1255 then use anchors (^ to match the beginning of the string, $ to match the end of the string`):

^(\d{2}-\d-\d{2}|\d{3})$

CodePudding user response:

As The fourth bird said, you're not allowing multiple digits in the second case. Also, if you want to validate against the whole input, you'll need anchors at the ends (which will also mean the alternation in the middle will need to be in a group [presumably a non-capturing group]); otherwise, the starting anchor would be in the first part of the alternation and the ending anchor would be in the second part of it.

So:

const rex = /^(?:\d{2}(-\d-\d{2})|(\d ))$/;
//           ^^^^                    ^ ^^

Example:

const rex = /^(?:\d{2}(-\d-\d{2})|(\d ))$/;
const tests = [
    {text: "12-1-12", expect: true},
    {text: "123", expect: true},
    {text: "12-1-1-12", expect: false},
];

for (const {text, expect} of tests) {
    const result = rex.test(text);
    console.log(`"${text}": ${result} (${!result === !expect ? "Good" : "*** ERROR"})`);
}
.as-console-wrapper {
    max-height: 100% !important;
}

  • Related