Regex in xpath is not recognized during TC execution


Could you please help me to locate an element with regex in xpath?
I need locate id that is ‘any12symbols’ + ‘-’ + ‘index’
but regex is not recognized during TC execution
I use following xpath:

//ng-dropdown-panel//div[contains(@class, 'scrollable-content')]//div[@id='${const}-${index}']

and following keyword'Object Repository/id intervention index', [('const') : '.{12}', ('index') : id_OfHighlightedItem_int1+1]), FailureHandling.CONTINUE_ON_FAILURE)
  • id_OfHighlightedItem_int1 is integer

Thank you in advance for your help!

1 Like

The matches(string, regex) function was added in the XPath 2.0 specification. Browsers only supports the XPath 1.0. You can not use any Regular Expression in XPath on browser. It is not a defect of Katalon Studio at all.

However you can write an XPath expression equivalent to an regexp using XPath 1.0 string functions: substring(s, pos, len), substring-before(s1, s2), substring-after(s1, s2), string-length(s), translate(s1, s2, s3) in combination.

1 Like

I will show you an example how to write an XPath expression without regex.

I made a html file <projectDir>/page.html

<!DOCTYPE html>
<html lang="ja">
        <meta charset="UTF-8">
        <link rel="stylesheet" href="style.css">
            <div id="a6da1165cfca-3">Hello, world</div>

And I made a Test Case:

import java.nio.file.Path
import java.nio.file.Paths
import com.kms.katalon.core.configuration.RunConfiguration
import com.kms.katalon.core.testobject.ConditionType
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

TestObject makeTestObject(String id, String xpath) {
	TestObject tObj = new TestObject(id)
	tObj.addProperty("xpath", ConditionType.EQUALS, xpath)
	return tObj

Path projectDir = Paths.get(RunConfiguration.getProjectDir())
Path html = projectDir.resolve("page.html")
WebUI.setViewPortSize(800, 1000)

String xpath = """
//div[string-length(substring-before(@id, '-')) = 12]
     [string-length(translate(substring-before(@id, '-'), '1234567890abcdef', '')) = 0]

TestObject tObj = makeTestObject("div_hello", xpath)
WebUI.verifyElementPresent(tObj, 3)
String content = WebUI.getText(tObj)

WebUI.comment("content : ${content}")


When I ran it, I saw the following output:

Please note that the XPath expression in my sample Test Case works similar to the one you attempted with regex.

I think that it is not a big issue that we can not use the matches() function of XPath 2.0. We can always find an alternative expression without regex. You just want to get accustomed to utilizing XPath 1.0 String functions in combination.