我的值是这样的:

"Foo Bar" "Another Value" something else

什么正则表达式将返回括在引号中的值(例如Foo Bar和Another Value)?


当前回答

对于Microsoft VBA编码器子集的补充回答,只有一个人使用Microsoft VBScript正则表达式5.5库,这给出了以下代码

Sub TestRegularExpression()

    Dim oRE As VBScript_RegExp_55.RegExp    '* Tools->References: Microsoft VBScript Regular Expressions 5.5
    Set oRE = New VBScript_RegExp_55.RegExp

    oRE.Pattern = """([^""]*)"""


    oRE.Global = True

    Dim sTest As String
    sTest = """Foo Bar"" ""Another Value"" something else"

    Debug.Assert oRE.test(sTest)

    Dim oMatchCol As VBScript_RegExp_55.MatchCollection
    Set oMatchCol = oRE.Execute(sTest)
    Debug.Assert oMatchCol.Count = 2

    Dim oMatch As Match
    For Each oMatch In oMatchCol
        Debug.Print oMatch.SubMatches(0)

    Next oMatch

End Sub

其他回答

如果你试图查找只有特定后缀的字符串,比如点语法,你可以尝试这样做:

\"([^\"]*?[^\"]*?)\". 本地化

其中。本地化是后缀。

例子:

打印(“这是我需要归还的东西”。本地化+“所以是这个”。本地化+ "but this is not")

它会捕捉到“这是我需要归还的东西”。本地化和“这也是”。本地化但不是“but this is not”。

与亚当的答案不同,我有一个简单但有效的答案:

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

如果你想要得到引号中的内容,只需添加圆括号:

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

$1匹配引号字符,$2匹配内容字符串。

接受的答案的RegEx返回值,包括它们的寻源引号:“Foo Bar”和“Another Value”作为匹配。

下面是RegEx,它只返回引号之间的值(正如提问者所要求的那样):

仅使用双引号(使用捕获组#1的值):

"(.*?[^\\])"

仅使用单引号(使用捕获组#1的值):

'(.*?[^\\])'

Both(使用捕获组#2的值):

([']) "(. *? 1 \ [^ \ \])

-

全部支持转义和嵌套引号。

特别的是,这些答案都不会产生一个正则表达式,其中返回的匹配是所要求的引号内的文本。MA-Madden尝试了,但只获得了内部匹配,而不是整个匹配。一种实际的方法是:

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

这方面的例子可以在这个演示https://regex101.com/r/Hbj8aP/1中看到

The key here is the the positive lookbehind at the start (the ?<= ) and the positive lookahead at the end (the ?=). The lookbehind is looking behind the current character to check for a quote, if found then start from there and then the lookahead is checking the character ahead for a quote and if found stop on that character. The lookbehind group (the ["']) is wrapped in brackets to create a group for whichever quote was found at the start, this is then used at the end lookahead (?=\1) to make sure it only stops when it finds the corresponding quote.

唯一的另一个复杂之处在于,由于前向查询实际上并不使用结束引号,它将被开始后向查询再次找到,这将导致匹配同一行上结束引号和开始引号之间的文本。在开头引用(["']\b)上加上一个单词边界有助于解决这个问题,尽管理想情况下我想跳过前瞻,但我认为这是不可能的。中间允许转义字符的部分直接取自亚当的回答。

这个版本

转义引号的说明 控制回溯 /(["'])((?:(?!\ 1 )[^\\]|(?:\\\\)*\\[^\\])*)\ 1 /