【问题标题】:How to replace string in order如何按顺序替换字符串
【发布时间】:2021-05-10 17:45:19
【问题描述】:

我想按顺序替换一些值

例如,下面是 xpath 的示例

/MCCI_IN200100UV01[@ITSVersion='XML_1.0'][@xsi:schemaLocation='urn:hl7-org:v3 MCCI_IN200100UV01.xsd']
/PORR_IN049016UV[r]/controlActProcess[@classCode='CACT']
[@moodCode='EVN']/subject[@typeCode='SUBJ'][1]/investigationEvent[@classCode='INVSTG']
[@moodCode='EVN']/outboundRelationship[@typeCode='SPRT'][relatedInvestigation/code[@code='2']
[@codeSystem='2.16.840.1.113883.3.989.2.1.1.22']][r]/relatedInvestigation[@classCode='INVSTG']
[@moodCode='EVN']/subjectOf2[@typeCode='SUBJ']/controlActEvent[@classCode='CACT']
    [@moodCode='EVN']/author[@typeCode='AUT']/assignedEntity[@classCode='ASSIGNED']/assignedPerson[@classCode='PSN']
        [@determinerCode='INSTANCE']/name/prefix[1]/@nullFlavor",

并且,我想按顺序提取 [r] 并根据元素的数量从 [0] 替换为 [n]。

如何替换 [r] ?

【问题讨论】:

    标签: python xpath replace information-extraction


    【解决方案1】:

    const txt = `/MCCI_IN200100UV01[@ITSVersion='XML_1.0'][@xsi:schemaLocation='urn:hl7-org:v3 MCCI_IN200100UV01.xsd']
    /PORR_IN049016UV[r]/controlActProcess[@classCode='CACT']
    [@moodCode='EVN']/subject[@typeCode='SUBJ'][1]/investigationEvent[@classCode='INVSTG']
    [@moodCode='EVN']/outboundRelationship[@typeCode='SPRT'][relatedInvestigation/code[@code='2']
    [@codeSystem='2.16.840.1.113883.3.989.2.1.1.22']][r]/relatedInvestigation[@classCode='INVSTG']
    [@moodCode='EVN']/subjectOf2[@typeCode='SUBJ']/controlActEvent[@classCode='CACT']
        [@moodCode='EVN']/author[@typeCode='AUT']/assignedEntity[@classCode='ASSIGNED']/assignedPerson[@classCode='PSN']
            [@determinerCode='INSTANCE']/name/prefix[1]/@nullFlavor",`;
            
    const count = (txt.match(/\[r\]/g) || []).length; // count occurrences using RegExp
    
    let replacements; // set replacement values in-order
    switch (count) {
      case 0:
        break
      case 1:
        replacements = ["a"];
        break;
      case 2:
        replacements = ["___REPLACEMENT_1___", "___REPLACEMENT_2___"];
        break;
      case 3:
        replacements = ["d", "e", "f"];
        break;
    }
    
    let out = txt; // output variable
    for (let i = 0; i < count; i++) {
      out = out.replace("[r]", replacements[i], 1); // replace each occurrence one at a time
    }
    
    console.log(out);

    【讨论】:

      【解决方案2】:

      str.replace()。例如:

      >>> 'test[r]test'.replace('[r]', '[0]')
      'test[0]test'
      

      这是上面的docs

      【讨论】:

        猜你喜欢
        • 2022-01-21
        • 2020-01-12
        • 2015-12-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-18
        • 1970-01-01
        • 1970-01-01
        • 2012-09-16
        相关资源
        最近更新 更多