【问题标题】:Split text which is outside the tags and exclude tags names too拆分标签之外的文本并排除标签名称
【发布时间】:2015-08-13 04:52:33
【问题描述】:
regex = /<(\w+)\b[^<>]*>[\s\S]*?<\/\1>/g; 

x="Hello - <phone full="9087456311"> My Number</phone>9087456300<phone full="">9087456311</phone>"; 

splittedText = x.split(regex);

结果:splittedText = ["RSVP -", "phone", "9087456300", "phone", ""]

预期:splittedText = ["RSVP -", "9087456300", ""]

在这里,我不希望“电话”作为它的标签名称。我得到的是,正则表达式似乎是正确的,因为它匹配完美(在这种情况下 - [“我的号码”,“9087456311”])但如果我拆分它,在其中给出标签名称(在本例中为电话)

参考我之前的问题: Need regex to find text outside the tags ONLY javascript

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    而不是拆分,只需匹配并从中获取。

    [^<>]*(?=<(\w+)\b[^<>]*>[\s\S]*?<\/\1>)
    

    查看演示。

    https://regex101.com/r/uF4oY4/9

    var re = /[^<>]*(?=<(\w+)\b[^<>]*>[\s\S]*?<\/\1>)/gm; 
    var str = 'Hello - <phone full="9087456311"> My Number</phone>9087456300<phone full="">9087456311</phone>';
    var m;
    
    while ((m = re.exec(str)) !== null) {
        if (m.index === re.lastIndex) {
            re.lastIndex++;
        }
        // View your result using the m-variable.
        // eg m[0] etc.
    }
    

    【讨论】:

      【解决方案2】:

      拆分插入反向引用然后反向引用变为空字符串似乎存在一些问题。我不确定为什么会这样。无论如何,这是一种解决方案:

      var code = 'gXop8pdsf';
      var replaced = x.replace(regex, code);
      var splittedText = replaced.split(code);
      splittedText = splittedText.filter(function(value) {
        if (value != '') return true; //filters through array to remove empty strings
      });
      

      【讨论】:

        猜你喜欢
        • 2021-09-03
        • 2015-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-07
        • 2021-05-28
        • 1970-01-01
        相关资源
        最近更新 更多