String.matches doesn't work with?

Hi,
I don’t understand why does the following regex does not print “Hello”. Doesn’t ? mark mean (matches one character)? Thanks in advance.

String role = “ball”
if(role.matches(“b?ll”) == true)
{
System.out.println(“Hello”)
}

NO.

An article to learn Regex in Java/Groovy:


You expect "?" to stand for a single character; That is a semantics named “glob” of file names, which is effective in bash command line only. “glob” is not equal to Regular expression.

1 Like

Regular expression example in Groovy:

def inputs = ["ball", "bill", "bull", "tall"]
def regex = "b\\w?ll"
inputs.each { String s ->
    if (s.matches(regex)) {
        println "${s} matches ${regex}"
    } else {
        println "${s} doesn't match ${regex}"
    }
}

When I executed, i got the following output in the console:

ball matches b\w?ll
bill matches b\w?ll
bull matches b\w?ll
tall doesn't match b\w?ll

1 Like