2016-01-21 67 views
0

我有一个XML,我正在寻找特定标记(在本例中为“FirstName”),并且只有在空格前面有 - 字符时才删除值中的空格。如何使用RegEx删除XML中的空间使用样式表使用RegEx

换句话说,我想保留空格,如果没有 - 前面的话。我想要使​​用带有RegEx匹配和替换功能的XSL样式表来执行此操作。

预期结果为:萨姆 - 路易斯,“SAM-”和“路易斯”之间消除空间

<?xml version="1.0" encoding="utf-8"?> 
<NCV Version="1.14"> 
    <Invoice> 
     <customer> 
      <customerId>12785</customerId> 
      <FirstName>Sam- Louise</FirstName> 
      <LastName>Jones</LastName> 
     </customer> 
    </Invoice> 
</NCV> 

回答

1

您可以使用下面的正则表达式匹配中

(\<FirstName\>.*?-)\s+ 

,并与第一捕获更换组$1

正则表达式匹配(\<FirstName\>.*?-)\s+

  1. \<FirstName\>.*?-:文字<FirstName>后跟任何字符非贪婪,直到找到第一个连字符。这个匹配被添加到捕获的组中。
  2. \s+:匹配一个或多个空格字符。

将其替换为$1,将删除连字符后的空格。

+0

[演示](https://regex101.com/ r/bQ4pD1/3) – Tushar

+0

谢谢@Tushar,字符< and >需要在样式表中转义 – SAP

1

这是一种可能的XSLT:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> 
    <xsl:output method="html" encoding="UTF-8" indent="yes" /> 
    <xsl:strip-space elements="*"/> 

    <xsl:template match="FirstName"> 
     <FirstName> 
      <xsl:value-of select="replace(., '-\s+', '-')"/> 
     </FirstName> 
    </xsl:template> 

    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 
</xsl:transform> 

xsltransform.net demo

输出:

<NCV Version="1.14"> 
    <Invoice> 
     <customer> 
     <customerId>12785</customerId> 
     <FirstName>Sam-Louise</FirstName> 
     <LastName>Jones</LastName> 
     </customer> 
    </Invoice> 
</NCV> 
+0

谢谢@ har07 – SAP