正则表达式匹配单引号或双引号中的文本 [英] regex match text in either single or double quote

查看:561
本文介绍了正则表达式匹配单引号或双引号中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想匹配如下字符串:

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

并取回单个捕获(匹配),即外部单引号或双引号内的句子.

and get back a single capture (match) that is the sentence inside the outer single or double quotes.

^The sentence is (?:(?:'([^']*)')|(?:"([^"]*)"))$

上面的正则表达式给了我 2 个捕获的组,其中一个是空的,另一个包含所需的句子.

The above regex gives me back 2 captured groups, one of them empty and the other containing the desired sentence.

^The sentence is (['"])(.*)\1$

返回引号(单引号或双引号)作为第一组,句子作为第二组.

Returns the quotation mark (single or double quote) as the 1st group and the sentence as the 2nd group.

如果我让第一组不被捕获,

If I make the first group non-capturing,

^The sentence is (?:['"])(.*)\1$

然后我不能使用后来对捕获组的引用.(当然,\1 不再指单引号或双引号匹配)

then I cannot use the later reference to the captured group. (the \1 is, of course, no longer referring to the single or double quote match)

有没有办法让组的捕获"可以稍后在正则表达式中引用,但其捕获的值未在匹配列表中返回?

Is there a way to have groups whose "capture" can be referenced later in the regex, but whose captured value is not returned in the list of matches?

或者其他一些方法来解决我的(看似简单的)问题.

Or some other way to solve my (seemingly simple) problem.

推荐答案

这个似乎有效:

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

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

如果你需要一个小组.

演示如下:链接

它有效,因为 * 是一个贪婪的量词,所以你不必知道最后是什么类型的引用.* 将尽可能多.

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.

这篇关于正则表达式匹配单引号或双引号中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆