Franmcod
Franmcod

Reputation: 359

Test for specific number of words to match, with a known separator with Regex in Js

i'm trying to check wether a string matches a set of values and they are seperated by a ; It needs to have ; as a separator. I go this new RegExp(/\b(Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo)\b/, 'gi').test(str)

If i pass:

Thanks in advance.

[EDIT] code:

const WEEK_DAYS_GROUP_REGEX = /\b(Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo)\b/;

const res = new RegExp(WEEK_DAYS_GROUP_REGEX, 'i').test('Segunda;Terçaa');

console.log(res) // gives true

Upvotes: 1

Views: 36

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

The /\b(Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo)\b/ pattern with gi modifiers matches any of the alternatives as a whole word, it does not guarantee that the whole string consists of these values only, let alone the ; delimiter.

You may use

^(<ALTERNATIONS>)(?:;(<ALTERNATIONS>))*$

See the pattern demo.

In JS, you do not need to use that long pattern, you may build the pattern dynamically:

const strs = ["Segunda;Terça", "Segundaaa", "Segunda;Terçaa"];
const vals = "Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo";
let rx = new RegExp("^(?:" + vals + ")(?:;(?:" + vals + "))*$", "i");
console.log(rx);
for (let s of strs) {
  console.log(s,"=>",rx.test(s));
}

Note that the non-capturing groups (?:...) are preferred when there is no need extracting submatches, group values.

Upvotes: 1

Related Questions