XSLT - Check if pattern exists in an element string

浪尽此生 提交于 2019-12-21 20:38: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>

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/18907483/xslt-check-if-pattern-exists-in-an-element-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!