簡體   English   中英

Javascript從文本中提取與正則表達式匹配的字符串

[英]Javascript extract strings that match regex from text

我試圖從與 4chan 引號格式匹配的段落中獲取一組字符串: >>1111111>>開頭,后跟 7 位數字。

>>1111000
>>1111001
Yes, I agree with those sentiments. 

>>1111000>>1111001都將從上面的文本中提取出來,然后我將其拆分為后面的數字。

您可以使用此正則表達式

/[>]{2}[0-1]{7}/

您可以使用以下內容匹配以 2 >字符開頭后跟 7 個數字的行:

 const regex =/^[>]{2}[\\d]{7}$/gm; const text = `>>1234567 >>6548789 foo barr`; const matches = text.match(regex); console.log(matches);

似乎有一些答案,但由於這是一個主題,我想更好地理解這里是我的兩分錢。 過去, 這個答案對我有很大幫助,在線正則表達式網站也很棒,例如這個

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Parse Test</title> </head> <body> <div > <text id="ToParse"> >>1111000 <br> >>1111001 <br> Yes, I agree with those sentiments. </text> </div> <script> try { var body = document.getElementById('ToParse').innerHTML; console.log(body); } catch (err) { console.log('empty let body,' + " " + err); } function parseBody () { // from HTML // function parseBody (body) { // const regex = /(&gt;&gt;)([0-9]*)\\w+/gm; // from JS const regex = /(>>)([0-9]*)\\w+/gm; const body = ` >>1111000 <br> >>1111001 <br> Yes, I agree with those sentiments.`; let m; while ((m = regex.exec(body)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); } }; parseBody(body); // </script> </body> </html>

就像@spyshiv說的,你可以像這樣匹配字符串:

var string = '>>1111000';
var matches = string.match(/[>]{2}[0-1]{7}/);
console.log(matches);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM