tags:

views:

51

answers:

2

How can I parse the following string:

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

to obtain the bracketed values, i.e.

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

+4  A: 

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"]

hrnt
A: 

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
Beanish