简体   繁体   中英

Ruby regex parse string for two sets of numbers?

I have been using Rubular.com to come up with a regex pattern to try to parse this string for the values 596 and 777 and put them in an array:

Current mouse position: 596,777

I have been building this in IRB and testing it with t.scan(/(?:\\d)/)

This yields: ["4", "5", "1", "1", "1", "3", "7"] which is not correct.

Does anyone have any pointers?

You have forgotten to put a quantifier :

t.scan(/\d+/)

The quantifier + means one or more

Note: The non-capturing group (?:...) is useless.

str = "Current mouse position: 596,777"

x, y = str.split()[-1].split(",")
puts x, y


--output:--
596
777

...

str = "Current mouse position: 596,777"

x = str[-7..-5]
y = str[-3..-1]
puts x, y

--output:--
596
777

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM