【问题标题】:RegEx to parse complex xml javascript正则表达式解析复杂的 xml javascript
【发布时间】:2011-02-06 06:42:57
【问题描述】:

我在受限的 Javascript 环境中工作,没有 xml 解析器或 dom 访问权限。

格式如下:

<gd:phoneNumber rel="http://schemas.google.com/g/2005#mobile">206 555 1212</gd:phoneNumber>

我需要获取 string[] 值:mobile, 206 555 1212

值每次都会不同,但标签始终相同。

然后我需要能够替换值,例如:home、555-555-5555

这可以在正则表达式中完成吗?

【问题讨论】:

  • Jamie Zawinski,1997 年:“有些人在遇到问题时会想“我知道,我会使用正则表达式。”现在他们有两个问题。 ... :)
  • 在 atrib/val 的上下文中哪些部分保持不变? google.com/g/...#mobile 呢?该标签中还有其他 attr/val 吗?这是在xml的上下文中吗?
  • 是的,当然可以使用正则表达式来完成。然而,Javascript 的正则表达式实现并不是很强大;它甚至无法正确处理 Unicode。不过,this 可能会给你一些想法。

标签: javascript xml regex parsing


【解决方案1】:

fast-xml-parser 仅基于正则表达式。您可以将其包含在您的项目中。

//var xml2json = require('fast-xml-parser').parse;
var jsonObj = xml2json('<gd:phoneNumber rel="http://schemas.google.com/g/2005#mobile">206 555 1212</gd:phoneNumber>', {ignoreNameSpace : true});
console.log(jsonObj.phoneNumber); // "206 555 1212"

或者,如果您自己制作正则表达式,我建议您使用正则表达式来捕获匹配的字符串,正如@DaveWard 在他的回答中所建议的那样,而不是使用replace

【讨论】:

    【解决方案2】:

    【讨论】:

    • 这很有帮助,但我就是无法正确使用语法。 jquery是
    【解决方案3】:

    这是我目前所拥有的,并且它有效,但有更好的方法吗?

    "<gd:phoneNumber rel=http://schemas.google.com/g/2005#mobile>206 555 1212</gd:phoneNumber>".replace(/#.*</g, '#home>111-111-1111<')
    

    返回:

    "<gd:phoneNumber rel=http://schemas.google.com/g/2005#home>111-111-1111</gd:phoneNumber>"
    

    所以我可以注入新值

    "<gd:phoneNumber rel=http://schemas.google.com/g/2005#mobile>206 555 1212</gd:phoneNumber>".match(/#.*</g)[0].replace(/[#<]/g, "").split(/>/)
    

    返回: [“移动”,“206 555 1212”]

    允许我获取值

    【讨论】:

      【解决方案4】:

      这会检索匹配项并执行替换:

      var testString = '<gd:phoneNumber rel=http://schemas.google.com/g/2005#mobile>206 555 1212</gd:phoneNumber>';
      
      var regex = /.*#(\w+)">(.*)</i;
      
      // matches[1] will be "mobile" and matches[2] will be "206 555 1212"
      var matches = regex.exec(testString);
      
      // Replace #mobile with #home
      testString = testString.replace(matches[1], 'home');
      
      // Replace the phone number with 555 555 5555
      testString = testString.replace(matches[2], '555 555 5555');
      

      只要这些值与 XML 元素的其余内容之间没有重叠,这些简单的替换就可以工作(例如,如果 schemas.google.com 网址在 #mobile 之前的某处包含字符串 mobile,这不会不工作)。只要是这样,这是更简单的替换方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-25
        • 1970-01-01
        • 2015-04-29
        • 2020-07-06
        • 1970-01-01
        • 2015-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多