6

n個のドットを持たない文字列を見つける方法が必要なため、この正規表現を作成しています。ただし、これまでのところ、正規表現は次のとおりです。

"^(?!\\.{3})$"

私がこれを読む方法は、文字列の開始と終了の間に、3ドットより多かれ少なかれ存在する可能性がありますが、3ドットは存在しない可能性がありますhello.here.im.greetings 。私はJavaで書いているので、Perlのようなフレーバーです。Javaでは必要ないので、中括弧をエスケープしていません。何かアドバイスはありますか?

4

2 に答える 2

5

あなたは正しい方向に進んでいます:

"^(?!(?:[^.]*\\.){3}[^.]*$)"

期待どおりに動作します。

あなたの正規表現は

^          # Match the start of the string
(?!\\.{3}) # Make sure that there aren't three dots at the current position
$          # Match the end of the string

したがって、空の文字列にしか一致しませんでした。

私の正規表現の意味:

^       # Match the start of the string
(?!     # Make sure it's impossible to match...
 (?:    # the following:
  [^.]* # any number of characters except dots
  \\.   # followed by a dot
 ){3}   # exactly three times.
 [^.]*  # Now match only non-dot characters
 $      # until the end of the string.
)       # End of lookahead

次のように使用します。

Pattern regex = Pattern.compile("^(?!(?:[^.]*\\.){3}[^.]*$)");
Matcher regexMatcher = regex.matcher(subjectString);
foundMatch = regexMatcher.find();
于 2013-01-15T12:47:05.463 に答える
1

正規表現は、3つの連続するドットではなく「一致する」だけです。あなたの例は、文のどこにも3つのドットを一致させたくないことを示しているようです。

これを試して:^(?!(?:.*\\.){3})

デモ+説明: http: //regex101.com/r/bS0qW1

代わりにティムズの答えをチェックしてください。

于 2013-01-15T12:49:31.837 に答える