my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Match asterisk with regexp Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Match asterisk with regexp" Watch "Match asterisk with regexp" New topic

Match asterisk with regexp

joe mo

Joined: Sep 23, 2007
Posts: 2
How do you match the asterisk character in a regular expression using Java. I tried escaping with a slash to no avail.
marc weber

Joined: Aug 31, 2004
Posts: 11343

Welcome to JavaRanch!

The API for java.util.regex.Pattern explains...
Backslashes within string literals in Java source code are interpreted as required by the Java Language Specification as either Unicode escapes or other character escapes. It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler.

So a regex of "\\*" (with two backslashes) will match an asterisk.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Rob Spoor

Joined: Oct 27, 2005
Posts: 19552

Please note that the regex itself is \*
You have to add the second slash only in Java source code to escape the first \

Just like in Java, \ is the escape character in regexes.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Match asterisk with regexp
Similar Threads
servlet mapping
While loop question from SCJP 5.0
asterisk program possible to do in module way
Regular Expression: what is wrong here?
Invoking method in packaged class