[英]Ruby/Regex parsing strings
I'd like to take a string and split it into an array only if its format is valid 我想取一个字符串并将其拆分为一个数组,只要其格式有效
Valid formats for the string include: 字符串的有效格式包括:
key: Bob value: 5000
key: Jane value: 6000,700,100
An invalid format, besides key:
or value:
being spelled wrong: 除
key:
或value:
之外的无效格式,其拼写错误:
key: Bob value: 6000,,,,100
I've been using gets
to get a line and trying to use this code: 我一直在使用
gets
来获得一行,并尝试使用以下代码:
if line =~ /key:\s\d+\svalue:\s([\d+]+,?)*/
# do stuff
end
I also tried using ===
but both just return true / not nil for both valid and invalid strings. 我也尝试使用
===
但是对于有效和无效的字符串,它们都只返回true / not nil。 How can I ensure that multiple consecutive commas is considered invalid? 如何确保多个连续逗号被视为无效?
I tend to use split in situations like this: 我倾向于在以下情况下使用split:
str = "key: Bob value: 5000,330,200"
=> "key: Bob value: 5000,330,200"
arr = str.split
=> ["key:", "Bob", "value:", "5000,330,200"]
if arr[0] == "key:" && arr[2] == "value:" && arr[3].split(",").none?(&:empty?)
# do stuff
end
Easier for me to suss out. 对我来说更容易打扰。
"affirmative" match : “肯定”匹配 :
^key:\\s\\w+\\svalue:\\s(\\d+,?)+$ //better validation
^(?!.*,,).*$ //simple negative lookahead
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.