开发者

Parsing a String in Ruby for multiple values?

How can I parse the following string:

Phone + 300 mins & unlimited开发者_如何学JAVA texts - 24 month plan $25

to obtain the bracketed values, i.e.

Phone + [300] mins & [unlimited] texts - [24] month plan $[25]


Depends, if they all look like that, then:

/Phone \+ (\w+) mins & (\w+) texts - (\d+) month plan \$(\w+)/

That assumes that a plan may contain unlimited minutes.

You can use the regex like this:

str =  "Phone + 300 mins & unlimited texts - 24 month plan $25"
regex =  /Phone \+ (\w+) mins & (\w+) texts - (\d+) month plan \$(\w+)/
match = regex.match(str).to_a

now match is ["Phone + 300 mins & unlimited texts - 24 month plan $25", "300", "unlimited", "24", "25"]


Match can also be abbreviated with the =~

so:

string =~ /Phone\s*\+\s*(\w*)\s*mins\s*&\s*(\w*)\s*texts\s*-\s*(\w*)\s*month\s*plan\s*\$(\w*)/

performs a match on the string with the regex on the right hand side.

You can also directly access the value of a group (the parts of the regex within parens) utilizing $1 etc

so in this case

minutes = $1
texts = $2
months = $3
cost = $4
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜