user3437460
user3437460

Reputation: 17454

Java Regex match zero times or once

I was playing around with Regex in Java, and I wanted to match a string which has zero or one occurrence of a dot .. So I want any strings with a single dot or no dot to return true, and a string with two or more dots to return false.

According to the Java documentation:

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 . zero or one time, but it prints false.

Did I misinterpret the meaning of ?? What can I do to make it match zero or one time only?

Upvotes: 3

Views: 6141

Answers (3)

user3437460
user3437460

Reputation: 17454

A slight variation from the given solutions as proposed by user anubhava, we can use:

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

According to him, . does not need to be escaped within the square brackets [ ]


All credits to user anubhava

Upvotes: 0

Jimmy T.
Jimmy T.

Reputation: 4190

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.

Upvotes: 6

JimmyJames
JimmyJames

Reputation: 1403

This might be what you want: ([^\.]*\.[^\.]*)? It will match any string that contains any number of non-dots, followed by a single dot followed by any number of non-dots that occurs zero or once. You'll need to escape your escapes for Java string literals which looks like this: ([^\\.]*\\.[^\\.]*)?

Upvotes: 1

Related Questions