[英]JavaScript Match Using regexp
I'm trying to extract some data from a large string and I was wondering if it is possible to use regexp. 我试图从一个大字符串中提取一些数据,我想知道是否可以使用regexp。 Currently, I'm using javascript.
目前,我正在使用javascript。 For example:
例如:
This is some [example] text for my javascript [regexp] [lack] of knowledge.
With this string, I would like to generate a JSON array with the texts that are between the square brackets. 使用此字符串,我想使用方括号之间的文本生成一个JSON数组。
example, regexp, lack
I hope someone can help me do this in a simple way so I can understand how it works. 我希望有人能以一种简单的方式帮助我做到这一点,以便我能理解它的工作原理。 Thank you in advance for your help.
预先感谢您的帮助。 Daniel!
丹尼尔!
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/ http://jsfiddle.net/mE7EQ/
I wrote one up real quick, if you have any questions about it, let me know! 我很快就写了一个,如果您有任何疑问,请告诉我!
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.