JustAnotherDev
JustAnotherDev

Reputation: 475

Java matches doesn't match

Could someone explain why the following statement in java returns false?

boolean results = "123/#".matches("\\d/#")

I tried to escape the forward slash and the pound sign, but this was being marked as redundant..

Upvotes: 0

Views: 38

Answers (2)

Toto
Toto

Reputation: 91415

\d matches a single digit, if you want to match 1 or more, add a quantifier \d+.

boolean results = "123/#".matches("\\d+/#")

Upvotes: 0

grawity_u1686
grawity_u1686

Reputation: 16247

String.matches() in Java requires the full string to match the regex, as if it was bounded with ^ ... $. So imagine that you're actually testing the regex ^\d/#$ here.

To allow the string to contain anything else before/after, you must explicitly allow that in the regex using .* (anything), for example:

boolean results = "123/#".matches(".*\\d/#.*")

Upvotes: 1

Related Questions