regex match text in either single or double quote

前端 未结 3 402
自闭症患者
自闭症患者 2020-12-10 14:13

I want to match strings like:

The sentence is \'He said \"Hello there\"\'
The sentence is \"He said \'Hello there\'\"

and get back a single

相关标签:
3条回答
  • 2020-12-10 14:43

    Very sad, but such an elegant and accurate way does not work:

    (["'])(?:\\\1|[^\1]+)*\1
    

    But we can change it a little bit, and all works fine:

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

    https://regex101.com/r/dKdBMT/2

    I would like to make sure that this regexp will work in all cases: please more test it.

    0 讨论(0)
  • 2020-12-10 14:43

    You want to make sure the quote symbols are properly matched, so a quote starting with a single quote ends with a single quote. Also, the regex should allow for escaping a quote symbol with a backslash if it's the same symbol (double or single quote symbol) bounding the string. Try this:

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

    These samples match this regex:

    'sing"le q\'uote'

    "dou\"ble 'quote"

    0 讨论(0)
  • 2020-12-10 14:49

    This one seems to work:

    (?:'|").*(?:'|")
    

    or

    ((?:'|").*(?:'|"))
    

    if you need a group.

    Here's the demo: link

    It works, because * is a greedy quantifier, so you don't have to know what kind of quote is in the end. * will take as much as possible.

    0 讨论(0)
提交回复
热议问题