1

文字列に一致する正規表現が必要です

  1. のような特殊文字で始まり、[#.>+~]その後に小文字の ASCII 単語が続くか、または
  2. のような異なる特殊文字のみで構成され*ます。

特殊文字はグループ番号 1 に、次の単語 (または 2 番目のケースでは空の文字列) はグループ番号 2 にキャプチャする必要があります。

最初のケースは で処理/^([#\.>+~]?)([a-z]+)$/できますが、2 番目のケースをこの正規表現に入れて次の結果を得るにはどうすればよいですか。

"#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 に答える