简体   繁体   English

正则表达式查找字符串中的任何双引号字符串

[英]Regex to find any double quoted string within a string

I'm trying to get a regex that will find a double quoted strings within a double quoted string.我正在尝试获取一个正则表达式,它将在双引号字符串中找到双引号字符串。 For example:例如:

"some text "string 1" and "another string" etc" “一些文本“字符串 1”和“另一个字符串”等”

I would like to pick out "string 1" and "another string".我想挑出“字符串1”和“另一个字符串”。

I got as far as \\"[^\\"]*\\" but this will match "some text " in the example. I basically need to ignore the first and last quotes and match within that.我得到了\\"[^\\"]*\\"但这将匹配示例中的“一些文本”。我基本上需要忽略第一个和最后一个引号并在其中匹配。

Edit: The example mentioned doesn't have literal quotes surrounding it, but it is a Javascript string.编辑:所提到的示例周围没有文字引号,但它是一个 Javascript 字符串。 The example regex is matching the entire string first.示例正则表达式首先匹配整个字符串。 My Javascript is as follows.我的Javascript如下。

 var string = 'some "text" etc'; var pattern = new RegExp('\\"[^\\"]*\\"/g'); var result = pattern.exec(string); console.log("result: ", string); // some "text" etc

So it could be my implementation of regex in Javascript that is the problem.所以这可能是我在 Javascript 中实现正则表达式的问题。

Don't escape the " . And just look for the text between quotes (in non greedy mode .*? ) like:不要转义" 。只需查找引号之间的文本(在非贪婪模式下.*? ),例如:

 var string = 'some text "string 1" and "another string" etc'; var pattern = /".*?"/g; var current; while(current = pattern.exec(string)) console.log(current);

This works also:这也有效:

var s = "\"some text \"string 1\" and \"another string\" etc\"" ""some text "string 1" and "another string" etc""
s.match(/(?!^)".*?"/g)

Result: [""string 1"", ""another string""]

The negative look ahead will not match the first quote because it's at the beginning, causing all others to match, ignoring the last one, since it doesn't have another quote following.负面展望不会匹配第一个引用,因为它位于开头,导致所有其他引用匹配,忽略最后一个引用,因为它后面没有另一个引用。 This assumes there won't be any white space before the first quote of course.当然,这假设在第一个引用之前不会有任何空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM