Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Match asterisk with regexp

 
joe mo
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
How do you match the asterisk character in a regular expression using Java. I tried escaping with a slash to no avail.
Thanks
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20555
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic