Neil Neil - 1 month ago 12
Ruby Question

Ruby Regular Expression If String has optional period, confirm only 0-2 digits follow

I want to write a regular expression with the following conditions:


  • string can contain 0-1 period


    • if the string contains a period: have no more than two digits afterwards




Test conditions:

The following would pass the regex:

'foo'
'foo.'
'foo.1'
'foo.11'
''
'.'
'.1'
'.11'
'1'
'1.'
'1.1'
'1.11'


The following would fail the regex:

'.123'
'.1234'
'.a'
'.1a'
'.aa'
'.aaa'


I have been playing around with trying to get this to work on rubular for a bit now and am struggling.

Answer
a = %w(foo foo. foo.1 foo.11 . .1 .11 1 1. 1.1 1.11 .123 .1234 .a .1a .aa .aaa) + ['']
a.grep(/^\w*\.?(\d){0,2}$/m)
 => ["foo", "foo.", "foo.1", "foo.11", ".", ".1", ".11", "1", "1.", "1.1", "1.11", ""] 
Comments