0

I have a the following code

StringToSearchIn ="Hello word (Figure 1)"; 
patternString= "word (Figure 1)" 
Pattern pattern = Pattern.compile(patternString);       
Matcher matcher = pattern.matcher(StringToSearchIn);
matcher.find()

This is returning 0, as '( or )' is not recognized, when I change to patternString= "word \\(Figure 1\\)" , is returning the match counter as 1 Is there a way to change my patternString to search for '(' and replace with '\\(' dynamically before creating a pattern.

Thanks in advance.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
ndippy
  • 11
  • 1
  • 5
  • I'm not sure, but it sounds like what you're asking for is a regular expression to match "(Figure 1)"? Or '(' followed by anything, followed by ')'? – MadConan May 13 '15 at 17:26
  • 1
    Thank you all, it worked with Pattern.quote(String regex); – ndippy May 13 '15 at 17:33

4 Answers4

2

Use Pattern#quote(String regex):

Pattern pattern = Pattern.compile(Pattern.quote(patternString));
M A
  • 71,713
  • 13
  • 134
  • 174
2

You can use the LITERAL flag.

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#LITERAL:

Enables literal parsing of the pattern. When this flag is specified then the input string that specifies the pattern is treated as a sequence of literal characters. Metacharacters or escape sequences in the input sequence will be given no special meaning.

So in your code:

Pattern pattern = Pattern.compile(patternString, Pattern.LITERAL);
Mark Leiber
  • 3,118
  • 2
  • 13
  • 22
0
Pattern.quote("$5");

From this answer:

How to escape text for regular expression in Java

Community
  • 1
  • 1
StormeHawke
  • 5,987
  • 5
  • 45
  • 73
0

Java has built in Pattern conversion.

A Pattern is A compiled representation of a regular expression. A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.

A typical invocation sequence is thus paternString.replace

 Pattern p = Pattern.compile("a*b");
 Matcher m = p.matcher("aaaaab");
 boolean b = m.matches();

A matches method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement

 boolean b = Pattern.matches("a*b", "aaaaab");

If compile is not handling your parenthesis you can do add a method that injects string replacement.

patternString = patternString.replace('(', '\('); 
patternString = patternString.replace(')', '\)'); 
penguin
  • 724
  • 5
  • 11