我想匹配以下字符串:
The two sentences are 'He said "Hello there"' and "She said 'goodbye' and 'another sentence'"
其中每个句子由单引号或双引号分隔,并且可以在句子中包含相反的双引号或单引号 .
正则表达式应该返回2个匹配 - 每个句子1个 . 对于上面的例子:
He said "Hello there"
She said 'goodbye' and 'another sentence'
以下正则表达式接近:
^The two sentences are (?:'|")(.*)(?:'|") and (?:'|")(.*)(?:'|")$
但是因为第一个表达式组贪婪到任何单引号或双引号,上面的例子实际上返回:
He said "Hello there"' and "She said 'goodbye
another sentence'
如果我这样做会很容易:
^The two sentences are ('|")(.*)\1 and ('|")(.*)\3$
但是后来我也回到了捕获组的比赛 - 所以我得到了4场比赛 - 单引号,第一句,双引号,第二句 .
关于如何做这种事情(匹配字符串分隔符的开始和结束)的任何好主意,同时“丢弃”分隔符匹配,然后返回分隔字符串中匹配的内容?
2 回答
这是两个单独的表达 . 你最好这样处理它们
您可能需要将各个部分括起来才能使用
|
,但您应该明白这一点 .Build @daniu
你为什么不这样做呢?
(?:"([^"]*)"|'([^']*)')
https://regex101.com/r/hpuoia/1