Search code examples
stringxpathtextnumbers

xpath to select a pattern with any number + "specific string"


xpath for such span with text containing a number and a string

<span>10 days</span> 

I have tried this one - //span[contains(text(), 'days') and matches(text(), '\d+ days')] but its not working


Solution

  • XPath 1.0 doesn't support regexps. Fortunately, ^\d+ days$ is simple enough for you to write an equivalent condition with the limited set of string functions that XPath 1.0 provides:

    //span[
        substring-after(text()," ") = "days" and
        substring-before(text()," ") != "" and
        translate(substring-before(text()," "), "0123456789", "") = ""
    ]
    

    example

    input:

    <div>
        <!-- matching examples -->
        <span>10 days</span>
        <span>365 days</span>
        <span>2 days</span>
    
        <!-- non-matching examples -->
        <span> days</span>
        <span>100 </span>
        <span>X days</span>
        <span>10 months</span>
        <span> 3 days</span>
        <span>4 days </span>
        <span>5  days</span>
        <span>6days</span>
    </div>
    

    result:

    10 days
    365 days
    2 days