【问题标题】:XSLT remove string from value with regexXSLT 使用正则表达式从值中删除字符串
【发布时间】:2018-01-15 21:59:19
【问题描述】:

我想使用 XSLT 和正则表达式从 XML 中的节点值中查找和删除字符串:

<result>
   <item>
      <variantname>Apple 90 430 29 S</variantname>
   </item>
   <item>
      <variantname>Apple 90 480 29 M</variantname>
   </item>
   <item>
      <variantname>Carrot 60 420 27 M</variantname>
   </item>
   <item>
      <variantname>Carrot 60 440 27 S</variantname>
   </item>
</result>

我想从上面的 XML 中删除 430 和 480,即 'Apple 90' 和 '29' 之间的字符串。

输出应如下所示:

 <result>
       <item>
          <variantname>Apple 90 29 S</variantname>
       </item>
       <item>
          <variantname>Apple 90 29 M</variantname>
       </item>
       <item>
          <variantname>Carrot 60 27 M</variantname>
       </item>
       <item>
          <variantname>Carrot 60 27 S</variantname>
       </item>
 </result>

编辑

我只是在想以某种方式可以将“可替换”字符串作为变量传递?

removestarpartfromthis = "'苹果 90 * 29','胡萝卜 60 * 27'"

【问题讨论】:

  • 那么Apple 的输出variantnames 中的27s 是从哪里来的?你想在星号之前和之后允许什么变化,真的是Apple 90Carrot 60吗?
  • @MartinHonnen 这是一个很大的错字,我在迈克尔凯的解决方案下用我的小想法更新了问题+评论。我希望现在更清楚了。

标签: xml xslt saxon


【解决方案1】:

作为替代方案,您似乎也可以只对空白进行标记,然后删除第三个标记:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="variantname/text()">
      <xsl:value-of select="tokenize(., '\s+')[position() ne 3]"/>
  </xsl:template>

</xsl:stylesheet>

如果你想使用一个正则表达式列出你想匹配并保留或删除的部分文字文本,那么也许

  <xsl:template match="variantname/text()">
      <xsl:value-of select="replace(., '((Apple 90|Carrot 60)\s+)[0-9]+\s+(.*)', '$1$3')"/>
  </xsl:template>

给你一个想法。在线示例http://xsltfiddle.liberty-development.net/pPgCcop

【讨论】:

  • 这也是一个不错的解决方案,但在这种情况下,我有一些项目,我不想删除第三部分,这就是为什么我正在寻找一个可以指定可替换的解决方案部分。
  • @Adrian,我添加了一个使用替换和带括号的子表达式的示例。
【解决方案2】:

你需要类似的东西

<xsl:template match="variantname/text()">
  <xsl:value-of select="replace(., 'Apple 90 [0-9]+ 29', 'Apple 90 29')"/>
</xsl:template>

【讨论】:

  • 这个解决方案很好用。同时我更新了问题,是否可以将可替换部分作为变量传递?我想替换多个项目,如果可能的话,我想避免将每个可替换项目作为单独的模板。
  • 当然,XPath 允许您在任何可以使用字符串文字的地方使用表达式(例如变量引用或对 concat() 的调用)。
  • 有些事情在我的脑海中,但我真的不知道如何正确地做到这一点:(其中 * 是分隔符),然后是: --->其中 $valuespartA 是 Apple 90,$valuespartB 是 29,$valuespartA=Carrot 60, $valuespartB=27。
猜你喜欢
  • 2013-05-23
  • 1970-01-01
  • 2021-01-17
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
  • 2022-06-28
  • 2021-09-07
  • 1970-01-01
相关资源
最近更新 更多