XPath: match a whole word (using the match case function with a case-insensitive flag)

Using XPath, I would like to "Match the whole word" (option for the user, as in VS search).

It seems that the function containsand matchesoperate similarly, although coincidentally permits the use of type flags ifor case insensitivity.

In other words, I get the same results with these two XPath queries:

<pets>
    <dog name="Rupert" color="grey"/>
    <dog name="Ralph" color="brown"/>
    <cat name="Marvin the Cat" color="white"/>
    <cat name="Garfield the Cat" color="orange"/>
    <cat name="Cat" color="grey"/>
    <cat name="Fluffy" color="black"/>
</pets>

Matches XPath: //cat[descendant-or-self::*[@*[matches(.,'Cat')]]]
    returns:
    <cat name="Marvin the Cat" color="white"/>
    <cat name="Garfield the Cat" color="orange"/>
    <cat name="Cat" color="grey"/>


Contains XPath: //cat[descendant-or-self::*[@*[contains(.,'Cat')]]]
    returns:
    <cat name="Marvin the Cat" color="white"/>
    <cat name="Garfield the Cat" color="orange"/>
    <cat name="Cat" color="grey"/>

But I would like to use matchesto return results that match only the whole word "Cat":

<cat name="Cat" color="grey"/>

How can I customize a match query to match a whole word?

EDIT: I forgot to mention that I need to use the match function because I need a case-sensitivity flag.

+5
5

^ $ ?

//cat[descendant-or-self::*[@*[matches(.,'^Cat$')]]]

RegEx XQuery 1.0 XPath 2.0:

, ^ $. ^ , $ .

+5

?

//cat[@*='Cat']
+2

/.

matches() ; (^ cat $), "i", .

() ; (), , .

eq ; " " ( XPath, , API- ), . , , , , "i" ().

+2

, , "Cat", :

<cat name="Cat" color="grey"/>

There are different XPath expressions that select the desired item :

Using:

/*/cat[matches(@name, '^cat$', 'i')]

Or use:

/*/cat[lower-case(@name) eq 'cat']

XSLT Based Validation :

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <xsl:copy-of select=
   "/*/cat[matches(@name, '^cat$', 'i')]"/>
======
  <xsl:copy-of select=
   "/*/cat[lower-case(@name) eq 'cat']"/>

 </xsl:template>
</xsl:stylesheet>

when applied to the provided XML document:

<pets>
    <dog name="Rupert" color="grey"/>
    <dog name="Ralph" color="brown"/>
    <cat name="Marvin the Cat" color="white"/>
    <cat name="Garfield the Cat" color="orange"/>
    <cat name="Cat" color="grey"/>
    <cat name="Fluffy" color="black"/>
</pets>

this conversion evaluates two XPath expressions and copies the selected elements to the output file :

  <cat name="Cat" color="grey"/>
======
  <cat name="Cat" color="grey"/>
+2
source

It:

//cat[@*='Cat']

leads to:

<cat name="Cat" color="grey"/>

I checked with Xacobeo .

+1
source

All Articles