繁体   English   中英

使用正则表达式进行JavaScript匹配

[英]JavaScript Match Using regexp

我试图从一个大字符串中提取一些数据,我想知道是否可以使用regexp。 目前,我正在使用javascript。 例如:

This is some [example] text for my javascript [regexp] [lack] of knowledge.

使用此字符串,我想使用方括号之间的文本生成一个JSON数组。

example, regexp, lack

我希望有人能以一种简单的方式帮助我做到这一点,以便我能理解它的工作原理。 预先感谢您的帮助。 丹尼尔!

var str = "This is some [example] text for my javascript [regexp] [lack] of knowledge."
var regex = /\[(.*?)\]/g, result, indices = [];
while ( (result = regex.exec(str)) ) {
    indices.push(result[1]);
}
var text = 'some [example] text for my javascript [regexp] [lack] of knowledge.';
text.match(/\[(.*?)\]/g).map(function(m) {
    return m.substr(1, m.length - 2);
})
// => ["example", "regexp", "lack"]

http://jsfiddle.net/mE7EQ/

我很快就写了一个,如果您有任何疑问,请告诉我!

var a = 'This is some [example] text for my javascript [regexp] [lack] of knowledge.'
var results = a.match(/\[\w*\]/g);

alert(results[0] + ' ' + results[1] + ' ' + results[2]);

暂无
暂无

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

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