Jax Jax - 1 year ago 121
Ruby Question

Ruby .scan method returns empty using regex

So given a string like this

"\"turkey AND ham\" NOT \"roast beef\""
I need to get an array with the inner strings like so:
["turkey AND ham", "roast beef"]
and eliminate
's and
's that may or may not be there.

With the help of Rubular I came up with this regex

which returns the following 2 groups:

Match 1
1. turkey AND ham
Match 2
1. roast beef

however when I use it with
keep getting and empty array.

I looked at this and this other SO posts, and a few others, but can not figure out where I am going wrong

Here is the result from my rails console:

=> q = "\"turkey and ham\" OR \"roast beef\""
=> q.scan(/\\["']([^"']*)\\["']/)
=> []

["turkey AND ham", "roast beef"]

I shall also mention I suck at regex.

Answer Source

You regex is trying to match \, which won't match anything in the string, since the \ existed to escape the double quote, and won't be part of the string.

So if you remove \\ in your regex

res = q.scan(/["']([^"']*)["']/)

This will return a 2d array

res = [["turkey and ham"], ["roast beef"]]

Each inner array is all the matching groups from the regex, so if you have two capture groups in your regex, you will see two items in the inner array.

If you want a simple array, you can run flatten method on the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download