Rahul Tapali
Rahul Tapali

Reputation: 10137

Checking string with minimum 8 digits using regex

I have regex as follows:

     /^(\d|-|\(|\)|\+|\s){12,}$/

This will allow digits, (, ), space. But I want to ensure string contains atleast 8 digits. Some allowed strings are as follows:

      (1323  ++24)233
      24243434 43
      ++++43435++4554345  434

It should not allow strings like:

     ((((((1213)))
     ++++232+++

Upvotes: 3

Views: 3253

Answers (3)

Anirudha
Anirudha

Reputation: 32797

Use Look ahead within your regex at the start..

/^(?=(.*\d){8,})[\d\(\)\s+-]{8,}$/
  ---------------
          |
          |->this would check for 8 or more digits

(?=(.*\d){8,}) is zero width look ahead that checks for 0 to many character (i.e .*) followed by a digit (i.e \d) 8 to many times (i.e.{8,0})

(?=) is called zero width because it doesnt consume the characters..it just checks


To restict it to 14 digits you can do

/^(?=([^\d]*\d){8,14}[^\d]*$)[\d\(\)\s+-]{8,}$/

try it here

Upvotes: 7

sawa
sawa

Reputation: 168101

No need to mention ^, $, or the "or more" part of {8,}, or {12,}, which is unclear where it comes from.

The following makes the intention transparent.

r = /
  (?=(?:.*\d){8})    # First condition: Eight digits
  (?!.*[^-\d()+\s])  # Second condition: Characters other than `[-\d()+\s]` should not be included.
/x

resulting in:

"(1323  ++24)233" =~ r #=> 0
"24243434 43" =~ r #=> 0
"++++43435++4554345  434" =~ r #=> 0
"((((((1213)))" =~ r #=> nil
"++++232+++" =~ r #=> nil

Upvotes: 0

Jonas Elfström
Jonas Elfström

Reputation: 31428

Here's a non regular expression solution

numbers = ["(1323  ++24)233", "24243434 43" , "++++43435++4554345  434", "123 456_7"]

numbers.each do |number|
  count = 0
  number.each_char do |char| 
    count += 1 if char.to_i.to_s == char
    break if count > 7
  end
  puts "#{count > 7}"
end

Upvotes: 0

Related Questions