我的值是这样的:

"Foo Bar" "Another Value" something else

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


当前回答

这个版本

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

其他回答

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

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

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

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

"(.*?)"

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

在Python中,你可以这样做:

>>> import re
>>> string = '"Foo Bar" "Another Value"'
>>> print re.findall(r'"(.*?)"', string)
['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

更多的答案!这是我使用的解决方案

\"([^\"]*? 图标 [^\"]*?)\"

TLDR; 替换词图标与你所寻找的说语录,瞧!


它的工作方式是寻找关键字,而不关心引号之间的其他内容。 例如: id = " fb-icon " id = " icon-close " id = " large-icon-close " 正则表达式查找引号" 然后它寻找任何可能的字母组,而不是“ 直到找到图标 任何可能的字母组都不是" 然后它会寻找一个结束。”

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