1

I've got a couple strings and I need to pull characters out that appear between double quotes. The problem is, I want to grab them in groups.

var str = 'FF\"J"A4"L"';
var results = str.match(/\"(.*)\"/);

This returns everything between the first and last double quote. In this case it returns J"A4"L but what I need it to return is J and L.

The content between quotes is pretty much any unicode character like letters and numbers including as }, =, and @.

Any ideas on how to complete this with regex?

  • Use `RegExp#exec` in a loop to get Group 1 value of `/"(.*?)"/g`. Or `/"([^]*?)"/g` – Wiktor Stribiżew Jun 22 '16 at 23:24
  • 1
    I don't think this question is a duplicate of http://stackoverflow.com/q/22444/940217 It may be asked/answered elsewhere, but this is not the same case. – Kyle Falconer Jun 22 '16 at 23:27
  • /".*?"/ is not correct. It would be too greedy. – Kyle Falconer Jun 22 '16 at 23:31
  • I think it's also possible to do without a Regex. You can split the string by `\"` character and then filter it to get only odd results. See example [jsbin.example](http://jsbin.com/zobifof/edit?js,output) – Telman Jun 22 '16 at 23:39

2 Answers2

1

what you're looking for is this with the /g "global flag":

/("[^"]*")/g

In your example, it's like this:

var str = 'FF\"J"A4"L"';
var results = str.match(/("[^"]*")/g);

When doing this, results would be [""J"", ""L""], which contains the entire match (which is why the extra quotes are there).

If you wanted just the matched groups (which returns just the groups, not the whole match area), you would use exec:

var str = 'FF\"J"A4"L"';
var results = []
var r = /("[^"]*")/g
match = r.exec(str);
while (match != null) {
    results.push(match[1])
    match = r.exec(str);
}

Now, results is ["J", "L"]

Kyle Falconer
  • 8,302
  • 6
  • 48
  • 68
1

It sounds like the content between quotes is any character except for a quote, in which case you can get away with

/"([^"]*)"/
Andrew Rueckert
  • 4,858
  • 1
  • 33
  • 44