JS Regex前瞻

时间:2016-03-08 01:18:58

标签: javascript regex node.js

我希望能够匹配这些类型的字符串(逗号分隔,没有开头或尾随空格):

  

LaunchTool [0] .Label,LaunchTool [0] .URI,LaunchTool [1] .Label,LaunchTool [1] .URI,LaunchItg [0] .Label,LaunchItg [0] .URI,csr_description

规则用英语表示:

1) Zero or more instances of [] where the brackets must contain only one number 0-9
2) Zero or more instances of ., where . must be followed by a letter
3) Zero or more instances of _, where _ must be followed by a letter

我目前有这个正则表达式:

/^([a-z]){1,}(\[[0-9]\]){0,}(\.){0,}[a-z]{1,}$/i

我无法弄明白为什么

"aaaa"不匹配

furthemore,

"aaaa[0].a"匹配,但"aaaa[0]"不匹配...

谁知道什么是错的?我相信我可能需要先行才能确定。和_字符后跟一个字母?也许我可以避免它。

2 个答案:

答案 0 :(得分:1)

  1. 这个正则表达式可以匹配" aaaa",试着获得
  2. 的价值

    (/^([a-z]){1,}(\[[0-9]\]){0,}(\.){0,}[a-z]{1,}$/i).test("aaaa")

    1. " AAAA [0]"不匹配,因为表达式结尾有[a-z]{1,}。一次" [0]"由(\[[0-9]\]){0,}匹配,尾随[a-z]{1,}必须显示在字符串
    2. 的末尾

答案 1 :(得分:0)

使用可选的捕获组。示例:([a-z])?

以下是我最终的结果: /^((\w+)(\[\d+\])?\.?(\w+)?,?)+$/

Shorthands解释:

 * = {0,}
 + = {1,}
\w = [A-Za-z0-9_]
\d = [0-9]