我的值是这样的:

"Foo Bar" "Another Value" something else

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


当前回答

如果你试图查找只有特定后缀的字符串,比如点语法,你可以尝试这样做:

\"([^\"]*?[^\"]*?)\". 本地化

其中。本地化是后缀。

例子:

打印(“这是我需要归还的东西”。本地化+“所以是这个”。本地化+ "but this is not")

它会捕捉到“这是我需要归还的东西”。本地化和“这也是”。本地化但不是“but this is not”。

其他回答

我的解决方案如下

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

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

解释:

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

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

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

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

特别的是,这些答案都不会产生一个正则表达式,其中返回的匹配是所要求的引号内的文本。MA-Madden尝试了,但只获得了内部匹配,而不是整个匹配。一种实际的方法是:

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

这方面的例子可以在这个演示https://regex101.com/r/Hbj8aP/1中看到

The key here is the the positive lookbehind at the start (the ?<= ) and the positive lookahead at the end (the ?=). The lookbehind is looking behind the current character to check for a quote, if found then start from there and then the lookahead is checking the character ahead for a quote and if found stop on that character. The lookbehind group (the ["']) is wrapped in brackets to create a group for whichever quote was found at the start, this is then used at the end lookahead (?=\1) to make sure it only stops when it finds the corresponding quote.

唯一的另一个复杂之处在于,由于前向查询实际上并不使用结束引号,它将被开始后向查询再次找到,这将导致匹配同一行上结束引号和开始引号之间的文本。在开头引用(["']\b)上加上一个单词边界有助于解决这个问题,尽管理想情况下我想跳过前瞻,但我认为这是不可能的。中间允许转义字符的部分直接取自亚当的回答。

我喜欢《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 )[^\\]|(?:\\\\)*\\[^\\])*)\ 1 /

我喜欢Eugen Mihailescu的解决方案,在允许转义引号的同时匹配引号之间的内容。然而,我发现了一些转义的问题,并提出了以下正则表达式来解决它们:

(['"])(?:(?!\1|\\).|\\.)*\1

它做到了这一点,而且仍然非常简单,易于维护。

演示(包含更多的测试用例;请随意使用并扩展它)。


PS:如果你只是想在引号之间的内容完全匹配($0),并不怕性能惩罚使用:

(?<=(['"])\b)(?:(?!\1|\\).|\\.)*(?=\1)

不幸的是,没有引号作为锚,我不得不添加一个边界\b,它不能很好地处理开始引号后的空格和非单词边界字符。

或者,修改初始版本,只需添加一个组,并从$2中提取字符串:

(['"])((?:(?!\1|\\).|\\.)*)\1

PPS:如果你只关注效率,那就选择Casimir和Hippolyte的解决方案;这是一个很好的例子。