如何在JavaScript中匹配字符串与文本模式?

时间:2014-06-15 15:08:08

标签: javascript regex

我有类似的东西:

<a href="Pages/MyLink_1_02.php" class="Style8">Text 1</a><br>
<a href="Pages/MyLink_1_03.php" class="Style8">Text 2</a><br>

如何找到所有Pages/MyLink_[NUM]_[NUM]

到目前为止,我已经:linksText.match(/\"Pages/MyLink_"/)但是还有一段距离。想法?

2 个答案:

答案 0 :(得分:3)

var regex = /Pages\/MyLink_(\d+)_(\d+)/g,
    match;
while ((match = regex.exec(data)) !== null) {
    console.log("Actual match ", match[0]);
    console.log("First number ", match[1]);
    console.log("Second number", match[2]);
}

<强>输出

Actual match  Pages/MyLink_1_02
First number  1
Second number 02
Actual match  Pages/MyLink_1_03
First number  1
Second number 03

Online Demo 1, with explanation of the RegEx

Regular expression visualization

Debuggex Demo

答案 1 :(得分:2)

[NUM]替换为(\d+)。那样做。

/Pages\/MyLink_(\d+)_(\d+)\.php/

你可以得到这样的数字:

var regex = /Pages\/MyLink_(\d+)_(\d+)\.php/;
var str = "Pages/MyLink_1_02.php";
var arr = str.replace(regex,"$1,$2").split(",");

arr[0]将包含第一个数字,而arr[1]将包含第二个数字。