How can I match a quote-delimited string with a regex?

前端 未结 9 717
一生所求
一生所求 2020-12-01 05:05

If I\'m trying to match a quote-delimited string with a regex, which of the following is \"better\" (where \"better\" means both more efficient and less likely to do somethi

9条回答
  •  离开以前
    2020-12-01 05:59

    Using the negated character class prevents matching when the boundary character (doublequotes, in your example) is present elsewhere in the input.

    Your example #1:

    /"[^"]+"/ # match quote, then everything that's not a quote, then a quote

    matches only the smallest pair of matched quotes -- excellent, and most of the time that's all you'll need. However, if you have nested quotes, and you're interested in the largest pair of matched quotes (or in all the matched quotes), you're in a much more complicated situation.

    Luckily Damian Conway is ready with the rescue: Text::Balanced is there for you, if you find that there are multiple matched quote marks. It also has the virtue of matching other paired punctuation, e.g. parentheses.

提交回复
热议问题