问题描述
我想按顺序替换一些值
例如,下面是一个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] ?
解决方法
用str.replace()
。例如:
>>> 'test[r]test'.replace('[r]','[0]')
'test[0]test'
这是上面的 docs。
,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);