3

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+++

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

12 Comments

Haha, first Some1.Kill.The.DJ beats me to the answer, then @JanDvorak beats me to the comment. :D So this is what I got: ^(?=(?:.*\d){8})(?:\d|-|\(|\)|\+|\s){12}
@Amadan you can't stop matching the main regex when you collect enough data. There might be undesired characters in the string.
Also, I suggest you use rubular.com for Ruby queries - Ruby's regular expressions are quite a bit more powerful than JavaScript's, modifiers are different, and if that's not reason enough, Rubular has a quite nice interface.
@JanDvorak: Good point. ^(?=(?:.*\d){8})(?:\d|-|\(|\)|\+|\s){12,}$
You can clean up the main part to: [\d\s\(\)+-]{12,}
|
0

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

2 Comments

What about non-allowed characters ?
He mentions ´[(),\s]´ in the question but the example strings also contains ´[\+]´. The definition seems unclear.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.