【问题标题】:javascript regexp match tag namesjavascript 正则表达式匹配标签名称
【发布时间】:2014-02-10 07:59:05
【问题描述】:

我不记得它的名字,但我相信你可以在 RegExp 对象中引用已经匹配的字符串。我想要做的是匹配给定字符串中的所有标签,例如

<ul><li>something in the list</li></ul>

RegExp 应该只能匹配相同的标签,然后我将使用递归函数将所有单独的匹配项放入一个数组中。如果我可以引用第一个匹配项,那么应该起作用的正则表达式是。

var reg = /(?:<(.*)>(.*)<(?:FIRST_MATCH)\/>)/g; 

匹配的数组应该包含

match[0] = "<ul><li>something in the list</li></ul>";
match[1] = "ul";
match[2] = ""; // no text to match
match[3] = "li";
match[4] = "something in the list";

感谢您的帮助

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您的意思似乎是反向引用(\1\2):

    var s = '<ul><li>something in the list</li></ul>';
    s.match(/<([^>]+)><([^>]+)>(.*?)<\/\2><\/\1>/)
    // => ["<ul><li>something in the list</li></ul>",
    //     "ul",
    //     "li",
    //     "something in the list"]
    

    结果和你想要的不完全一样。但重点是后向引用\1\2 匹配早先组匹配的字符串。

    【讨论】:

    • 您好,感谢您的回复,但这不起作用。自从您发布以来,我一直在阅读并不断发现在 Javascript 中无法进行反向引用。也许我可以在String.replace() 中传递一个函数,然后用它看到的第一个标签名称运行另一个替换,然后将它推送到一个数组中。我会看看我是否可以让它工作。
    • @synthet1c,不工作?在 Javascript 中可以进行反向引用。请参阅ideone.com/sdmFmq(示例运行)。另见Regular expression guide in MDN(在页面中找到back reference
    【解决方案2】:

    不可能使用正则表达式解析 HTML(如果您对细节感兴趣,那是因为 HTML 解析需要比正则表达式可以表达的有限状态自动机更强大的自动机类型 - 查找FSA 与 FST 以了解更多信息)。

    您也许可以通过一些技巧来解决特定问题,但是如果您想使用 Javascript 可靠地解析 HTML,那么还有其他方法可以做到这一点。在网上搜索:解析 html javascript,您将获得大量有关如何执行此操作的指示。

    【讨论】:

      【解决方案3】:

      我做了一个肮脏的解决方法。仍然需要努力思考。

      var str = '<div><ul id="list"><li class="something">this is the text</li></ul></div>';
      
      function parseHTMLFromString(str){
          var structure = [];
          var matches = [];
          var reg = /(<(.+)(?:\s([^>]+))*>)(.*)<\/\2>/;
          str.replace(reg, function(){
              //console.log(arguments);
              matches.push(arguments[4]);
              structure.push(arguments[1], arguments[4]);
          });
          while(matches.length){
              matches.shift().replace(reg, function(){
                  console.log(arguments);
                  structure.pop();
                  structure.push(arguments[1], arguments[4]);
                  matches.push(arguments[4]);
              });
          }
          return structure;
      }
      
      // parseHTMLFromString(str); // ["<div>", "<ul id="list">", "<li class="something">", "this is the text"]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-09
        • 2014-08-29
        • 1970-01-01
        • 2016-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多