Home > other >  How create regexp for reapeted pattern?
How create regexp for reapeted pattern?

Time:11-06

In string available only 3 parameters : C1 - number is only 0 or 1 R1 - number is only 0 or 1 A

String Example "C1-R1-C0-C0-A-R0-R1-R1-A-C1"

Smth like this /[CRA]\d-/gi only for each with separetor

OR better use split and map methods?

CodePudding user response:

If you are looking for a regular expression, something like this should work:

/^([CR][01]|A)(-([CR][01]|A))*$/

Essentially, we match a valid "parameter" as well as any number of "-parameter" after it. In context:

const string1 = 'C1-R1-C0-C0-A-R0-R1-R1-A-C1';
const string2 = 'invalid';

const testString = (string) => {
  return /^([CR][01]|A)(-([CR][01]|A))*$/.test(string);
};

console.log(testString(string1));
console.log(testString(string2));

Output:

true
false

CodePudding user response:

Use split and then filter with the regexp.

let string = "C1-R1-C0-C0-A-R0-R1-R1-A-C1";
let result = string.split('-').filter(el => /^([CR][01]|A)$/.test(el));
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related