2017-06-17 86 views
2

我有一串文字,其中可以包含特定的標籤。 示例:var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';Javascript正則表達式匹配並從字符串中獲取值

我想要做的是對<pause #></pause>標記執行正則表達式匹配。 對於找到的每個標籤,在這種情況下它是<pause 4></pause><pause 7></pause>。我想要的是獲取值47,以及字符串長度除以<pause #>...</pause>標記之間的字符串。

我現在所擁有的並不多。 但我無法弄清楚如何抓住所有的情況,然後遍歷每一個,並獲取我正在尋找的值。

我對這個功能看起來是這樣的,現在,它沒有多少:

/** 
* checkTags(string) 
* Just check for tags, and add them 
* to the proper arrays for drawing later on 
* @return string 
*/ 
function checkTags(string) { 

    // Regular expresions we will use 
    var regex = { 
     pause: /<pause (.*?)>(.*?)<\/pause>/g 
    } 

    var matchedPauses = string.match(regex.pause); 

    // For each match 
     // Grab the pause seconds <pause SECONDS> 
     // Grab the length of the string divided by 2 "string.length/2" between the <pause></pause> tags 
     // Push the values to "pauses" [seconds, string.length/2] 

    // Remove the tags from the original string variable 

    return string; 


} 

如果任何人都可以解釋我怎麼能做到這一點,我將非常感謝! :)

回答

1

match(/.../g)不保存子組,您將需要execreplace來做到這一點。這裏有一個replace爲基礎的輔助函數的例子來獲取所有的比賽:

function matchAll(re, str) { 
 
    var matches = []; 
 
    str.replace(re, function() { 
 
    matches.push([...arguments]); 
 
    }); 
 
    return matches; 
 
} 
 

 
var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>'; 
 

 
var re = /<pause (\d+)>(.+?)<\/pause>/g; 
 

 
console.log(matchAll(re, string))

既然你反正移除標籤,你也可以直接使用replace

0

爲起點,因爲你還沒有太多到目前爲止,你可以試試這個

/<pause [0-9]+>.*<\/pause>/g 

,而不是讓數量在那裏你匹配再次使用

/[0-9]+>/g 

爲了擺脫最近登錄>

str = str.slice(0, -1); 
1

你需要做一個循環來查找文本的正則表達式模式的所有匹配組。 匹配組是包含原始文本,匹配值和匹配文本的數組。

var str = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>'; 
 

 

 
function checkTags(str) { 
 

 
    // Regular expresions we will use 
 
    var regex = { 
 
     pause: /<pause (.*?)>(.*?)\<\/pause>/g 
 
    } 
 
    var matches = []; 
 
    while(matchedPauses = regex.pause.exec(str)) { 
 
     matches.push([matchedPauses[1], matchedPauses[2].length /2]); 
 
    }; 
 

 
    return matches; 
 

 
} 
 

 
console.log(checkTags(str));