2016-09-18 123 views
0

我想創建一個數組,其中包含傳遞我的正則表達式和子字符串的字符串。例如:結合.split()和.match()結果

['stringpart1', 'match1', 'stringpart2', 'match2', 'stringpart3']

這是我的正則表達式:new RegExp("<(\/)?" + tag + ".*?>", "g");

我使用的線沿線的一個頁面的源代碼串的東西:

"<html>\n 
    <meta class='a'/>\n 
    <meta class='b'/>\n 
    <div>\n 
     <p>test</p>\n 
    </div>\n 
</html>" 

如果我用我的.split(re)頁面的源代碼,我得到的值爲

['<html>\n', undefined, '\n', undefined, '\n', '<div>\n<p>test</p>\n</div>\n</html>]

其中字符串中匹配的值是undefined

['<meta class='a'/>', '<meta class='b'/>']

是否有可能產生以下結果的javascript函數:

當我使用.match(re),預期將返回所有匹配的值?

['<html>\n', "<meta class='a'/>", '\n', "<meta class='b'/>", '\n', '<div>\n<p>test</p>\n</div>\n</html>] 
+0

也許看看regex.exec這裏: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec – klikas

+0

什麼'正則表達式「預計會匹配? – guest271314

+0

你爲什麼這樣做?你打算如何處理結果?另外,在你的HTML中有哪些stringpart1和match1等字符串你聲稱要回來? – 2016-09-19 03:14:36

回答

3

編輯 - 我的解決方案是基於編輯之前原來的問題。我會修改,但實際上我認爲在對這個問題進行編輯之後,james emanon的回答很重要,我想出的任何東西都只是他所擁有的一切而已。

基於你所使用的正則表達式,看起來你所能做的就是選擇一個特定的html標籤並搜索你的內容,找出該標籤的所有出現位置,然後輸出開始和結束標籤加上內容到輸出數組中。

下面是實現這一目標的一種方法:以上repl.it link

const text = "<html><div>content</div>><div>content</div></html>"; 
const tag = "div"; 
const re = new RegExp("(<"+tag+">)(.*?)(<\/"+tag+">)", "g"); 
let final = []; 

let matches = text.match(re).map((m) => m.replace(/>(.)/, ">@@@$1") 
             .replace(/\<(?=[^\<]*$)/, "@@@<") 
             .split("@@@")); 

for (let i=0; i<matches.length; i++) { 
    for (let j=0; j<matches[i].length; j++) { 
     final.push(matches[i][j]); 
    } 
} 

console.log(final); 
2

P1xt的解決方案是好的。對於較短的版本,這個「似乎」工作 - 這是我做的一個快速工作。我假設undefined對應於'matches'數組。

var text = "<html>\n<meta class='a'/>\n<meta class='b'/>\n<div>\n<p>test</p>\n</div>\n</html>" 
var tag = "meta"; 
var re = new RegExp("<(\/)?" + tag + ".*?>", "gm") 
var matches = text.match(re) 

text.split(re).reduce((p,c) => { 
    (!c) ? p.push(matches.shift()) : p.push(c); 
    return p; 
}, [])