我的值是这样的:

"Foo Bar" "Another Value" something else

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


当前回答

很晚才回答,却喜欢回答

(\"[\w\s]+\")

http://regex101.com/r/cB0kB8/1

其他回答

一般来说,下面的正则表达式片段就是你要找的:

"(.*?)"

这使用了非贪婪的*?运算符来捕获下一个双引号之前的所有内容。然后,使用特定于语言的机制提取匹配的文本。

在Python中,你可以这样做:

>>> import re
>>> string = '"Foo Bar" "Another Value"'
>>> print re.findall(r'"(.*?)"', string)
['Foo Bar', 'Another Value']

我喜欢《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

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

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

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

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

猎人

echo 'junk "Foo Bar" not empty one "" this "but this" and this neither' | sed 's/[^\"]*\"\([^\"]*\)\"[^\"]*/>\1</g'

这将导致:>Foo Bar<><>但这<

在这里,为了清晰起见,我显示了><'s之间的结果字符串,也使用了这个sed命令的非贪婪版本,我们首先抛出' 's之前和之后的垃圾,然后用' ' 's之间的部分替换它,并用><'s包围它。

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