RegEx: Grabbing values between quotation marks

前端 未结 20 1234
暖寄归人
暖寄归人 2020-11-22 02:13

I have a value like this:

\"Foo Bar\" \"Another Value\" something else

What regex will return the

20条回答
  •  不思量自难忘°
    2020-11-22 02:34

    I liked Eugen Mihailescu's solution to match the content between quotes whilst allowing to escape quotes. However, I discovered some problems with escaping and came up with the following regex to fix them:

    (['"])(?:(?!\1|\\).|\\.)*\1
    

    It does the trick and is still pretty simple and easy to maintain.

    Demo (with some more test-cases; feel free to use it and expand on it).


    PS: If you just want the content between quotes in the full match ($0), and are not afraid of the performance penalty use:

    (?<=(['"])\b)(?:(?!\1|\\).|\\.)*(?=\1)
    

    Unfortunately, without the quotes as anchors, I had to add a boundary \b which does not play well with spaces and non-word boundary characters after the starting quote.

    Alternatively, modify the initial version by simply adding a group and extract the string form $2:

    (['"])((?:(?!\1|\\).|\\.)*)\1
    

    PPS: If your focus is solely on efficiency, go with Casimir et Hippolyte's solution; it's a good one.

提交回复
热议问题