我想用以下条件编写正则表达式:
测试条件:
以下传递正则表达式:
'foo'
'foo.'
'foo.1'
'foo.11'
''
'.'
'.1'
'.11'
'1'
'1.'
'1.1'
'1.11'
以下失败正则表达式:
'.123'
'.1234'
'.a'
'.1a'
'.aa'
'.aaa'
我一直在试图让它在rubular上工作一段时间并且正在努力。
答案 0 :(得分:1)
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", ""]
答案 1 :(得分:0)
r = /
\A # match beginning of string
[^.]* # match >= 0 characters other than a period
\.? # optionally match a period
\d{,2} # match 0-2 digits
\z # match end of string
/x # free-spacing regex definition mode
(%w| foo foo. foo.1 foo.11 . .1 .11 1 1. 1.1 1.11 ^$. | << '').all? { |s| s =~ r }
#=> true
(%w| .123 .1234 .a .1a .aa .aaa |).any? { |s| s =~ r }
#=> false