mjekov
mjekov

Reputation: 682

Matching dot at the beginning of a string using matches?

I'm trying to match a string, starting with a dot using java's matches method. Why this doesn't work:

".why?".matches("\\.*");

When I use a single slash, i'm getting an error for invalid escape sequence. Thanks in advance

Upvotes: 2

Views: 2953

Answers (2)

Ruediger
Ruediger

Reputation: 271

Just tried it myself. This works for me

System.out.println(".why?".matches("^\\..*"));

You where just missing one "." to match the "why?" part.

Upvotes: 1

Bart Kiers
Bart Kiers

Reputation: 170308

"\\.*" matches a string consisting of zero or more '.'s. It matches the following (quoted) strings:

""
"."
".."
"..."

(and so on)

You want: "\\..*" instead. Note that . by default does not match line breaks, so it wouldn't match the following string:

".Why? \n Not!"

For such string to be matched, you need to enable DOT-ALL: "(?s)\\..*"

Upvotes: 7

Related Questions