首页 > 解决方案 > 如何为重复模式创建正则表达式?

问题描述

在字符串中只有 3 个参数可用: C1 - 数字只有 0 或 1 R1 - 数字只有 0 或 1 A

字符串示例“C1-R1-C0-C0-A-R0-R1-R1-A-C1”

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

或者更好地使用拆分和映射方法?

标签: javascriptregex

解决方案


如果您正在寻找一个正则表达式,这样的事情应该可以工作:

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

本质上,我们匹配一个有效的“参数”以及它之后的任意数量的“-参数”。在上下文中:

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

输出:

true
false

推荐阅读