This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets 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: 19649

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
jQuery in Action, 2nd edition
subject: Match asterisk with regexp
Similar Threads
servlet mapping
Invoking method in packaged class
Regular Expression: what is wrong here?
asterisk program possible to do in module way
While loop question from SCJP 5.0