XSLT - Check if pattern exists in an element strin

2020-07-22 10:09发布

I have the following element as part of a larger XML

<MT N="NonEnglishAbstract" V="[DE] Deutsch Abstract text [FR] French Abstract text"/>

I need to do some formatting of the value in @V attribute, only if it contains anything like [DE], [FR] or any two capital letters representing a country code within square brackets.

If no such pattern exist, I need to simply write the value of @V without any formatting.

I can use an XSLT 2.0 solution

I was hoping that I could use the matches() function something like

<xsl:choose>
<xsl:when test="matches(@V,'\[([A-Z]{{2}})\]([^\[]+'">
//Do something
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="@V"/>
</xsl:otherwise>
</xsl:choose>

2条回答
祖国的老花朵
2楼-- · 2020-07-22 10:47

You have not posted anything about what you have tried. How about looking up translate function and translating the strings capital letters to something like "X". Then test that string result for the existence of [XX]. That alone would tell you whether you need to process it.

<xsl:variable name="result">
   <xsl:value-of select="translate(@V,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXX')"/>
</xsl:variable>

Then use that result and then test:

 contains($result, "[XX]")

No regex required, pure XSL 1.1

查看更多
beautiful°
3楼-- · 2020-07-22 10:53

I think all you need is:

matches(@V,'\[[A-Z][A-Z]\]')

You don't have to match the entire string to get a true() ... I tell my students to write as short a reg-ex as possible.

查看更多
登录 后发表回答