/ /電話番号のREGEX-Ruby-ruby、regex

電話番号のREGEX - Ruby - ルビー、正規表現

次のことのみを許可する電話番号検証用のREGEXを作成したい:

例とまったく同じ形式の7桁(5557865)。

私は正規表現になじみがないか、そうでなければ自分でこれに取り組むだろう。うまくいけば、それが十分な情報で、他に何か必要なことがあれば教えてほしい。

回答:

回答№1の場合は3

実例 https://regex101.com/r/oZ2yQ0/1

(d{7})

( matches the character ( literally
d{7} match a digit [0-9]
Quantifier: {7} Exactly 7 times
) matches the character ) literally

回答№2の場合は3

7桁の数字と一致させるだけであれば、d {7}または[0-9] {7}を使用できます。


回答№3の場合は1

だけですることができます

/d{7}/ #or
/d{1..7}/ #or
/d[0-9]{7}/

その d 数字に一致し、 {7} 桁数。


回答№4の場合は1

これに取り組むためのいくつかの方法があります:

# Ensure the number consists entirely of seven digits, nothing else.
number.match(/Ad{7}z/)

# Remove all non-digit characters (D) and test that the length is 7.
number.gsub(/D/, "").length == 7

# Test that this is either NNN-NNNN or NNNNNNN.
number.match(/Addd-ddddz/)

通常、妥当性を確認しながら、検証メソッドをできる限り寛大にします。