tags:

views:

81

answers:

4

Hello,

I have Java string:

String b = "/feedback/com.school.edu.domain.feedback.Review$0/feedbackId");

I also have generated pattern against which I want to match this string:

String pattern = "/feedback/com.school.edu.domain.feedback.Review$0(.)*";

When I say b.matches(pattern) it returns false. Now I know dollar sign is part of Java RegEx, but I don't know how should my pattern look like. I am assuming that $ in pattern needs to be replaced by some escape characters, but don't know how many. This $ sign is important to me as it helps me distinguish elements in list (numbers after dollar), and I can't go without it.

Thanks.

+3  A: 

You need to escape "$" in the regex with a "\", but as a "\" is an escape character in strings you need to escape the ":" itself.

You will need to escape any special regex char the same way, for example with ".".

String pattern = "/feedback/com\\.navteq\\.lcms\\.common\\.domain\\.poi\\.feedback\\.Review\\$0(.)*";
Colin Hebert
+3  A: 

In Java regex both . and $ are special. You need to escape it with 2 backslashes, i.e..

"/feedback/com\\.navtag\\.etc\\.Review\\$0(.*)"

(1 backslash is for the Java string, and 1 is for the regex engine.)

KennyTM
+2  A: 

Escape the dollar with \

String pattern = 
  "/feedback/com.navteq.lcms.common.domain.poi.feedback.Review\\$0(.)*";

I advise you to escape . as well, . represent any character.

String pattern = 
  "/feedback/com\\.navteq\\.lcms\\.common\\.domain\\.poi\\.feedback\\.Review\\$0(.)*"; 
madgnome
+9  A: 

Use

String escapedString = java.util.regex.Pattern.quote(myString)

to automatically escape all special regex characters in a given string.

Tim Pietzcker