简体   繁体   中英

Extract One of Several Numbers from a String

Let's say I've got something like:

{values="99999" name="22222" store="11111"}

with:

.match(/values="\d+/) 

would return:

values="99999

How can I get just the "99999" out of it?

I've tried

.match(/values="(\d+)/) 

which should return just the numbers I thought, but it doesn't.

Hope someone can help!

Cheers,

Try this regex,

.match(/values="(\d+)"/) 

For just only the number after values= , you could use look-behind and look-ahead

.match(/(?<=values=")(\d+)(?=")/) 

Explanation:

  • (?<=values=") Look-behind is used here. It sets the matching marker just after to the string values="
  • (\\d+) In regex () called capturing groups. It captures one or more digits.
  • (?=") Lookahead is used to check whether the following character after the digits is double quotes or not. If it's double quotes then only the preceeding digits would be matched.

Ruby 2+: Use \\K

Do this:

if subject =~ /values="\K\d+/
    match = $&
  • values=" matches literal characters
  • The \\K tells the engine to drop what was matched so far from the final match it returns
  • \\d+ matches your digits

If you use the .captures method and look inside the return value, you will find what you need.

#!/usr/bin/env ruby

string = '{values="99999" name="22222" store="11111"}'
one = string.match(/values="(\d+)/).captures

p one   => ["99999"]

Basing from everyone's answer I can also suggest adding .to_a.shift which would return the found value if found or nil if not. Example:

.match(/(?<=values=")(\d+)(?=")/).to_a.shift
.match(/values="\K(\d+)/).to_a.shift

Doing rescue nil may also apply but it's a little hacky or less safe.

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