javascript - 正则表达式 : Match a string enclosed in single quotes but don't match those inside double quotes

标签 javascript regex string

我想编写一个正则表达式来匹配用单引号括起来的字符串,但不应该匹配用双引号括起来的带有单引号的字符串。

示例 1:

a = 'This is a single-quoted string';

a 的整个值应该匹配,因为它用单引号括起来。

编辑:完全匹配应该是: '这是一个单引号字符串'

示例 2:

x = "This is a 'String' with single quote";

x 不应返回任何匹配项,因为单引号位于双引号内。

我试过 /'.*'/g 但它也匹配双引号字符串中的单引号字符串。

感谢您的帮助!

编辑:

为了更清楚

给定以下字符串:

The "quick 'brown' fox" jumps
over 'the lazy dog' near
"the 'riverbank'".

匹配应该只是:

'the lazy dog'

最佳答案

假设不必处理转义引号(这是可能的,但会使正则表达式复杂化),并且所有引号都正确平衡(不像 It's... "Monty Python's Flying Circus"! ),那么您可以查找后跟偶数个双引号的单引号字符串:

/'[^'"]*'(?=(?:[^"]*"[^"]*")*[^"]*$)/g

查看live on regex101.com .

解释:

'        # Match a '
[^'"]*   # Match any number of characters except ' or "
'        # Match a '
(?=      # Assert that the following regex could match here:
 (?:     # Start of non-capturing group:
  [^"]*" # Any number of non-double quotes, then a quote.
  [^"]*" # The same thing again, ensuring an even number of quotes.
 )*      # Match this group any number of times, including zero.
 [^"]*   # Then match any number of characters except "
 $       # until the end of the string.
)        # (End of lookahead assertion)

关于javascript - 正则表达式 : Match a string enclosed in single quotes but don't match those inside double quotes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22626579/

相关文章:

c# - 需要通过正则表达式从字符串中获取日期

C++ 字符串和字符串字面量比较

python - 正则表达式组恰好匹配 n 次

Javascript 浏览器识别

javascript - 从对象中获取子 JSON 值

javascript - 如何使用 JavaScript 在表格中动态插入带有选择框和选项的表格行?

regex - 使用正则表达式识别 pandas 列中的模式和清理数据

匹配字符串中的 Javascript 正则表达式

java - 检查字符串是否包含数组中的字符

javascript - 从特定类的所有选定选项创建数组