Javascript正则表达式反向引用索引

时间:2013-05-27 13:20:08

标签: javascript regex backreference

我需要一个正则表达式来匹配

的字符串
  1. 要么以[#.>+~]之类的特殊字符开头,后跟小写的ASCII字,要么
  2. 仅包含不同的特殊字符,例如*
  3. 特殊字符应在第1组中捕获,第2组中包含以下字(或第二种情况下为空字符串)。

    我可以使用/^([#\.>+~]?)([a-z]+)$/处理第一个案例,但是如何将第二个案例放入此正则表达式以实现以下结果:

    "#word"  -> 1 => "#", 2 => "word"
    "~word"  -> 1 => "~", 2 => "word"
    "##word" -> no match
    "+#word" -> no match
    "!word"  -> no match
    "*word"  -> no match
    "word"   -> 1 => "",  2 => "word"
    "*"      -> 1 => "*", 2 => ""
    "**"     -> no match
    "*word"  -> no match
    

1 个答案:

答案 0 :(得分:1)

这个正则表达式应该做你需要的:

/^([#~.>+](?=[a-z]+$)|[*](?=$))([a-z]*)$/

regex101.com

上查看

<强>解释

^          # Start of string
(          # Match and capture in group number 1:
 [#~.>+]   # Either: one "special character"
 (?=       #  but only if it's followed by
  [a-z]+   #   at least one lowercase ASCII letter
  $        #   and the end of the string.
 )         #  End of lookahead
|          # OR
 [*]       #  one (different) special character
 (?=$)     #  but only if the string ends right after it.
)          # End of the first capturing group
(          # Match and capture in group number 2:
 [a-z]*    # Zero or more ASCII lowercase letters
)          # End of the second capturing group
$          # End of string