Fendrix
Fendrix

Reputation: 566

Matching character * in Regex (Java)

Want to match the character * in

String s ="foobar*";

I want to get the exact character * with one regex character and I don't want to use exclude everything else like

s.matches("[^\w]");

Upvotes: 1

Views: 1584

Answers (2)

jlordo
jlordo

Reputation: 37843

to match the asterisk you need this regex:

Pattern asteriskPattern = Pattern.compile("\\*");

But I don't see a good use of that pattern. If all you want to do is check if your string contains it, use

boolean stringContainsAsterisk = string.contains("*");

or find it's index

int indexOfAsterisk = string.indexOf("*");

now the value is -1 if it does not contain the asterisk, or the value of it's index in the string.

Upvotes: 6

Michał Herman
Michał Herman

Reputation: 3587

What about following:

s.matches("\\*");

Upvotes: 2

Related Questions