JavaScript正则表达式在[]之间返回字符串

时间:2012-01-11 15:06:17

标签: javascript regex

我目前正在使用jQuery和JavaScript开展项目。 DOM中会有多个a个元素,可以使用rel属性对这些元素进行分组,例如jqgal[mygal1]

单击其中一个锚点后,我想提取方括号之间的值,并将其读入变量以供稍后在脚本中使用。例如,在以下标记中:

<a href="my_image_1.jpg" rel="jqgal[mygal1]"><img src="some_image.jpg" /></a>

RegularExpression应返回mygal1。我一直试图解决这个问题,到目前为止还没有发现太多(这是那些日子之一)。任何人都可以指出正确的正则表达式来执行此操作吗?如果有帮助,括号外的字符串将始终为jqgal[]

4 个答案:

答案 0 :(得分:1)

这样的事情应该会有所帮助:

$('a[rel^="jqgal"]').click(function () {
    var val = $(this).attr("rel").match(/jqgal\[(.*)\]/)[1];
    // Do what you need with the 'val'
});

答案 1 :(得分:0)

在您的rel属性上使用/^.*?\[(.*?)\]/正则表达式。 1 组(由第一个括号组捕获)的内容应该是您想要的。

var data = /^.*?\[(.*?)\]$/.exec(link.rel)[0];

答案 2 :(得分:0)

var str = "jqgal[mygal1]"
var re = /\[([^\]]+)\]/
console.log( str.match(re) );

解释reg exp

\[       find a [ character - the \ character escapes the [ so it matches the text
(        capture group start
[^\]]+   match any character that is not a ]
)        capture group end
\]       match a closing [ (not needed) 

答案 3 :(得分:0)

尝试使用此正则表达式:/jqgal\[(.*)\]/

它将搜索jqgal[]内的任何字符串。

示例:

"jqgal[mygal1]".match(/jqgal\[(.*)\]/)
> ["jqgal[mygal1]", "mygal1"]