我的值是这样的:

"Foo Bar" "Another Value" something else

什么正则表达式将返回括在引号中的值(例如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

其他回答

我的解决方案如下

(\[‘])。* 1 (? ! [s ^ \])

演示链接:https://regex101.com/r/jlhQhV/1

解释:

(["'])->匹配'或',一旦找到匹配,将其存储在反向引用\1中

.* ->贪婪的方法继续匹配所有内容0次或更多次,直到它在字符串末尾遇到'或"。遇到这种状态后,正则表达式引擎返回到上一个匹配字符,此时正则表达式结束,将移动到下一个正则表达式。

\1 ->匹配先前与第一个捕获组匹配的字符或字符串。

(?![^\s]) ->负前向,确保在之前的匹配之后不应该有任何非空格字符

这个版本

转义引号的说明 控制回溯 /(["'])((?:(?!\ 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包围它。

string = "\" foo bar\" \"loloo\""
print re.findall(r'"(.*?)"',string)

试试这个,就像一个魅力!!

\表示跳过字符

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

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

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

试着在这里。