1

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]

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.