1

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

  1. 要么以特殊字符开头,[#.>+~]然后是小写的 ASCII 字,或者
  2. 仅由不同的特殊字符组成,例如*.

特殊字符应在组号 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
4

1 回答 1

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
于 2013-05-27T13:28:07.537 回答