Problem capturing quoted items in regular expression

Discussion in 'JavaScript' started by peterlen, Jul 9, 2007.

  1. #1
    Hello,

    I am trying to capture all the quoted items in a string. For example, if the string is:

    I am from "the city" of "Green Bay"

    I want to be able to capture and retrieve "the city" and "Green Bay" from the string.

    When using either match or a Regexp:

    var res = str.match(/(".+")/g);
    or
    var regex = new RegExp(/(".+")/g);
    var arr = regex.exec(str);

    I always get one capture: "the city" of "Green Bay"

    It is grabbing all the text between the first " and the last " without considering that there are two separate quoted items.

    Does anyone know how to change the expression so that it first finds "the city" and then finds "Green Bay"?

    Thanks for any thoughts - Peter
     
    peterlen, Jul 9, 2007 IP
  2. Mike H.

    Mike H. Peon

    Messages:
    219
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #2
    var testStr = 'I am from "the city" of "Green Bay"';
    var quoted = testStr.match(/"[^"]+"/g);
    alert(quoted);
    Code (markup):
     
    Mike H., Jul 9, 2007 IP
  3. peterlen

    peterlen Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Mike,

    Thant worked great. Thanks!!!

    Peter
     
    peterlen, Jul 9, 2007 IP