针对特定内容定位正则表达式

时间:2015-04-20 07:00:34

标签: html regex

我想要家乡的所有数据:
我如何提高这个正则表达式

Hometown: ([^<]*) <br>

获得所有家乡:田地 目前它将首先停在那里,不会继续下一个Hometown:field

一些示例输入:

    <strong><a href="/search/company/company/94613582">Anchor sample Ltd</a></strong><br>
    BIS: 94613582 <br>
    Hometown: MONTREAL <br>


    <div class="hori"></div>

    <strong><a href="/search/company/company/046251945">Anchor sample Ltd</a></strong><br>
    BIS: 046251945 <br>
    Hometown: ALABAMA <br>


    <div class="hori"></div>

    <strong><a href="/search/company/company/041634545">Anchor sample Ltd</a></strong><br>
    BIS: 041634545 <br>
    Hometown: GEORGIA <br>


    <div class="hori"></div>

    <strong><a href="/search/company/company/487915646">Anchor sample Ltd</a></strong><br>
    BIS: 487915646 <br>
    Hometown: FLORIDA <br>


    <div class="hori"></div>

    <strong><a href="/search/company/company/165875487">Anchor sample Ltd</a></strong><br>
    BIS: 165875487 <br>
    Hometown: KANSAS <br>

2 个答案:

答案 0 :(得分:1)

在这里,您需要找到字符串“Hometown”,然后将名称本身捕获到捕获组中,然后仅使用第一个组并匹配它们您应该使用的所有/g使用exec方法的修饰符

var re = /Hometown: ([^<]+)\s/g; 
var str = '<strong><a href="/search/company/company/94613582">Anchor sample Ltd</a></strong><br>\n    BIS: 94613582 <br>\n    Hometown: MONTREAL <br>\n\n\n    <div class="hori"></div>\n\n    <strong><a href="/search/company/company/046251945">Anchor sample Ltd</a></strong><br>\n    BIS: 046251945 <br>\n    Hometown: ALABAMA <br>\n\n\n    <div class="hori"></div>\n\n    <strong><a href="/search/company/company/041634545">Anchor sample Ltd</a></strong><br>\n    BIS: 041634545 <br>\n    Hometown: GEORGIA <br>\n\n\n    <div class="hori"></div>\n\n    <strong><a href="/search/company/company/487915646">Anchor sample Ltd</a></strong><br>\n    BIS: 487915646 <br>\n    Hometown: FLORIDA <br>\n\n\n    <div class="hori"></div>\n\n    <strong><a href="/search/company/company/165875487">Anchor sample Ltd</a></strong><br>\n    BIS: 165875487 <br>\n    Hometown: KANSAS <br>';
var m;
 
while ((m = re.exec(str)) !== null) {
    document.getElementById("res").innerHTML += "<br>" + m[1];
}
<div id="res"/>

如果城市名称后面的空格是可选的,请使用

var re = /Hometown: ([^<]+)(?=\s*<)/g;

请参阅demo

答案 1 :(得分:0)

&#39;克&#39;应该设置修饰符。

g修饰符用于执行全局匹配(查找所有匹配项,而不是在第一次匹配后停止)。