簡體   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