Klnkmnk Klnkmnk - 1 year ago 95
Ruby Question

Ruby/Regex parsing strings

Hey Id like to take a string and only try to split the string into an array if the format is valid

Valid formats for the string include:
key: Bob value: 5000

key: Jane value: 6000,700,100

an invalid format besides key: and value: being spelled wrong includes

key: Bob value: 6000,,,,100

I've been using gets to get a line and trying to use

if line =~ /key:\s\d+\svalue:\s([\d+]+,?)*/

i also tried using === but both just return true / not nil for both valid and invalid commands. how would i account to not accept if there are multiple commas together?

Answer Source

"affirmative" match:

^key:\s\w+\svalue:\s(\d+,?)+$ //better validation

"negative" match:

^(?!.*,,).*$ //simple negative lookahead

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download