How can I parse the following string:
Phone + 300 mins & unlimited texts - 24 month plan $25
to obtain the bracketed values, ie
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.