我需要一个正则表达式来匹配
的字符串[#.>+~]
之类的特殊字符开头,后跟小写的ASCII字,要么*
。 特殊字符应在第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
答案 0 :(得分:1)
这个正则表达式应该做你需要的:
/^([#~.>+](?=[a-z]+$)|[*](?=$))([a-z]*)$/
上查看
<强>解释强>
^ # 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