0

I used the following expression

str.match(tag+"(\s*=\s*)((['"]*)(.+?)(['"]*)\1)");

where str is the string to be matched with and tag is a variable

For example the above expression should match

m="img"
m='img'

where tag=m;
But at the above mentioned lined I'm getting

SyntaxError: Unexpected token ]

4

2 回答 2

2

如果从正则表达式的末尾删除 /1,它适用于 m="img":

m(\s*=\s*)((['\"]*)(.*)(['\"]*))

"\1" 被替换为模式中第一个子模式的值,所以如果你想匹配 m="img";m='img' 你应该使用以下内容:

(m\s*=\s*)((['\"]*)(.*)(['\"]*)\1)

其中 m 是您的标签变量。

编辑:您可以在此处
测试您的 javascript 正则表达式。

于 2012-04-09T06:35:03.000 回答
1
  • 如前所述,引号应该被转义。
  • 反向引用也应该被转义。
  • 一旦您使用反向引用,就不需要第二组带引号,
  • 它是第三个括号组,其中包含引号,因此您需要 \3,而不是 \1
  • 并且几乎不需要匹配任何数量的引号,例如:m = '''img'''

考虑到所有这些点,可能会得到以下解决方案:

var tag = 'm';
"m='img'".match(tag+"(\s*=\s*)((['\"]?)(.+?)\\3)")
// ["m='img'", "=", "'img'", "'", "img"]
于 2012-04-09T06:32:51.050 回答