File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 19541

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
Consider Paul's rocket mass heater.
subject: Match asterisk with regexp
Similar Threads
Invoking method in packaged class
servlet mapping
Regular Expression: what is wrong here?
asterisk program possible to do in module way
While loop question from SCJP 5.0