私はJavaアプリケーション用に次の正規表現を持っています:
[\+0-9]+([\s0-9]+)?
上記の電話番号の表現を最小 4 桁、最大 7 桁に制限するにはどうすればよいですか? この {4,7} を式に追加するようなものかと思ったのですが、うまくいきません。
アドバイスをお願いします。
基本的に、私の電話番号は、+ 記号とそれに続く数字 (+004...) または数字のみ (004...) で始まり、数字の間に空白を含めることもできます (0 0 4...)。
この正規表現を試すことができます:
[+]?(?:[0-9]\s*){4,7}
説明:
[+]? // Optional + sign
(?:[0-9]\s*) // A single digit followed by 0 or more whitespaces
{4,7} // 4 to 7 repetition of previous pattern
サンプル テスト:
String regex = "[+]?(?:[0-9]\\s*){4,7}";
System.out.println("0045234".matches(regex)); // true
System.out.println("+004 5234".matches(regex)); // true
System.out.println("+00 452 34".matches(regex)); // true
System.out.println("0 0 4 5 2 3 4".matches(regex)); // true
System.out.println("004523434534".matches(regex)); // false
System.out.println("004".matches(regex)); // false
"\\+?(\\d ?){3,6}\\d"
は、オプションの + 記号の後に 4 ~ 7 個の数字と、数字の間にオプションの空白が続くものと一致するはずです。
上記と同様の構造ですが、次のものがあります: :? taken off
(なぜそこにあるのかわからない?)
[+]?([0-9]\s*){4,7}