javascript - 如何为重复模式创建正则表达式?
问题描述
在字符串中只有 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
或者更好地使用拆分和映射方法?
解决方案
如果您正在寻找一个正则表达式,这样的事情应该可以工作:
/^([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
推荐阅读
- python - Pandas: how to merge two dataframes on a column by keeping the information of the first one?
- typescript - Angular6 typescript 扩展方法 Observable
- facebook - 如何使用 API v3+ 获取 Facebook 群组帖子作者的数据
- google-chrome - 无法在 Chrome 无头模式下播放 DRM 内容
- c# - MouseEventHandler 的 MouseHook
- azure - Azure Functions v2 从 .Net Standard 更改为 .Net Core
- c# - 如何在 C# 中使用自定义正则表达式?
- node.js - Express:匹配url中语言代码的路由
- jackson2 - Jackson JsonProperty 未应用
- xml - 仅在根节点添加前缀 NS0