我的值是这样的:

"Foo Bar" "Another Value" something else

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


当前回答

我能够创建这个正则表达式来满足我的需求。

我需要匹配一个包含引号的特定值。它必须是完全匹配的,没有部分匹配可以触发命中

如。“test”不能与“test2”匹配。

reg = r"""(['"])(%s)\1"""
if re.search(reg%(needle), haystack, re.IGNORECASE):
    print "winning..."

猎人

其他回答

我一直在使用以下方法并取得了巨大的成功:

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

它还支持嵌套引号。

对于那些想要更深入地解释这是如何工作的人,这里是用户ephemerent的解释:

([""'])匹配引号;((?=(\\?))\2.)如果存在反斜杠,吞噬它,无论是否发生,匹配一个字符;* ?匹配多次(非贪婪,如不吃结尾引号);\1匹配相同的报价,是用于开幕。

我喜欢《Axeman》更广阔的版本,但也遇到了一些问题(游戏邦注:例如它并不匹配

foo "string \\ string" bar

or

foo "string1"   bar   "string2"

所以我试着修正它:

# opening quote
(["'])
   (
     # repeat (non-greedy, so we don't span multiple strings)
     (?:
       # anything, except not the opening quote, and not 
       # a backslash, which are handled separately.
       (?!\1)[^\\]
       |
       # consume any double backslash (unnecessary?)
       (?:\\\\)*       
       |
       # Allow backslash to escape characters
       \\.
     )*?
   )
# same character as opening quote
\1

以上所有的答案都很好....除了他们不支持所有的unicode字符!at ECMA Script (Javascript)

如果你是Node用户,你可能想要支持所有unicode字符的可接受答案的修改版本:

/(?<=((?<=[\s,.:;"']|^)["']))(?:(?=(\\?))\2.)*?(?=\1)/gmu

试着在这里。

对于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”。