Reputation: 1190
I have a specific RegEx question, simply because I'm wracking my brain trying to isolate one item, rather than multiple.
Here is my text I am searching:
"{\"1430156203913\"=>\"ABC\", \"1430156218698\"=>\"DEF\", \"1430156219763\"=>\"GHI\", \"1430156553620\"=>\"JKL", \"1430156793764\"=>\"MNO\", \"1430156799454\"=>\"PQR\"}"
What I would like to do is capture the key associated with ABC
as well as the key associated with GHI
The first is easy enough, and I'm capturing it with this RegEx:
/\d.*ABC/
maps to: "1430156203913\"=>\"ABC
.
Then, I'd just use /\d/
to pull out the 1430156203913 key that I'm looking for.
The second is what I'm having difficulty with.
This does not work:
/\d.*GHI/
maps to the start of the first digit to my final string (GHI) ->
1430156203913\"=>\"ABC\", \"1430156218698\"=>\"DEF\", \"1430156219763\"=>\"GHI
Question: How can I edit this second Regex to just capture 1430156219763?
Upvotes: 0
Views: 52
Reputation: 110675
This is one way you could do that:
def extract(str, key)
r = /
(?<=\") # match \" in a positive lookbehind
\d+ # match one or more digits
(?= # begin a positive lookahead
\"=>\" # match \"=>\"
#{key} # match value of key
\" # match \"
) # end positive lookahead
/x
str[r]
end
extract str, "ABC" #=> "1430156203913"
extract str, "GHI" #=> "1430156219763"
Upvotes: 1
Reputation: 5414
Try this one to capture only the key
\b\d+\b(?=\\"=>\\"GHI)
check this Demo
Notice I've added \b
around d+
just for a better perfromance
Upvotes: 1
Reputation: 34156
To capture all the keys and values, use String#scan.
pairs = s.scan /"(\d+)"=>"([[:upper:]]+)"/
# [["1430156203913", "ABC"],
# ["1430156218698", "DEF"],
# ["1430156219763", "GHI"],
# ["1430156553620", "JKL"],
# ["1430156793764", "MNO"],
# ["1430156799454", "PQR"]]
Then to get any k/v pair you want, hashify and find them.
Hash[pairs].invert.values_at('ABC', 'DEF')
# ["1430156203913", "1430156218698"]
Upvotes: 1
Reputation: 67968
\d[^,]*GHI
You can simply use this.See demo.
https://regex101.com/r/yW3oJ9/3
Upvotes: 1