我需要验证给定规范的字符串:
const string = 'd(iig(i)), d(iitm), d' // is valid
字符串主要代表一个或多个d
block ,可以不带括号,也可以为空括号。
每个 block 由逗号和可选空格分隔。
该 block 内可以有 g、i、t 或 m。只有 g 可以选择打开新括号。
我从这个正则表达式开始:
if (!/^[dgitm, ()]*$/.test(string)) {
throw Error('Pattern has invalid character')
}
但我不知道如何对待这些规范:
- 每个 block 必须用逗号分隔(可选加空格)
- 仅在 d block 之间允许有空格(可选)
- d 和 g 可以有以下括号; i、t 和 m 不应包含以下括号
- d 永远不会在任何括号内
有效
dd(ii)
d(i),d(g)
d(g(iig))
d(g(iig(i)))
无效
d(g(d)) // no nested d
d(x) // invalid character
d(i()) // no brackets for i (only d or g)
d(ii)d(ii) // missing comma
i // missing first level d
<小时/>
更新
删除了平衡括号的规范,因为这无法通过 regEx 进行测试。
最佳答案
^d+(\((g\(|[git](?!\()|\))+)*(,d+(\((g\(|[git](?!\()|\))+)*)*$
可以测试here .
说明:
^d+ The input must start with some 'd's (m>=1 times)
// First parenthesis' content:
(\((g\(|[git](?!\()|\))+)* The following can appear n>=0 times:
'(', then the following can appear p>=1 times:
'g', then one of the following:
- 'g('
- ')'
- 'g'/'i'/'t' - without a '(' after them
(using negative lookahead)
// Every other element (optional):
(,d+(\((g\(|[git](?!\()|\))+)*)* Starts with a ',d', ',dd' or ',ddd', etc.
then the same as the first parenthesis' content
正如我在评论中提到的,您无法使用正则表达式验证括号。但是,您可以为此实现现有算法,或者通过比较左括号和右括号的数量(显然应该相等)来获得初始验证的感觉。
编辑:谢谢@anubhava的更正
关于javascript - JS : Trying to test for a very specific pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48347496/