user3437460 user3437460 - 4 years ago 131
Java Question

Java Regex match zero times or once

I was playing around with Regex in Java and I wanted to match a String which has 0 or 1 occurrence of a dot

.
. So I want any Strings with a single dot or no dot to return true, and a String with 2 or more dots to return false.

According to the Java Docs:


X? X, once or not at all


So I have the following:

String str = "abc.def";
System.out.println(str.matches(".?"));


I was expecting
str
to match for
.
0 or 1 time, but it prints
false
.

My Question: Did I miss interpreted the meaning of
?
? What can I do to make it match 0 or 1 time only?

Answer Source

The correct pattern is:

^[^\\.]*\\.?[^\\.]*$

First any number of characters which are not a dot, then optionally one dot followed by any number of characters which are not a dot.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download