1

I wanted to create a custom regex matcher for Espresso so that I can check if the text on the screen contains time in format like HH:mm for example 23:34 or 04:23

I have a regex matcher class:

class RegexMatcher(private val regex: String) :
    BoundedMatcher<View, TextView>(TextView::class.java) {
    private val pattern = Pattern.compile(regex)

    override fun describeTo(description: Description?) {
        description?.appendText("Checking the matcher on received view: with pattern=$regex")
    }

    override fun matchesSafely(item: TextView?) =
        item?.text?.let {
            pattern.matcher(it).matches()
        } ?: false
}

And a function:

private fun withPattern(regex: String): Matcher<in View>? = RegexMatcher(regex)

The text on the screen says: Sometext 08:23 the time is of course dynamic

My UI check is written like this:

onView(withText(startsWith("Sometext"))).check(matches(withPattern("/(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/")))

But the test always fails and I don't know why. Even if I just use something as simple as /^Sometext it fails. Can anyone help me?

John Doe
  • 131
  • 10

1 Answers1

5

Your regex pattern doesn't include the preceding part of the string. You'll want to include something to capture that Sometext portion. What you use to capture that beginning portion depends on what you expect it to be. If it will only ever be non-digits, you could use .* (matches any character, 0 to infinity times) or \D* (matches any non-digit character, 0 to infinity times). If you know you have specifications that, say, you'll always have a string that is something like The time is: {time}, you could simply add the specified string.

/.*(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/ /\D*(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/ /The time is: (0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/

I'd recommend playing around with a regex tool to get your regex just right. My preferred one is Regex101.

agoff
  • 5,818
  • 1
  • 7
  • 20