Mahesh Gupta
Mahesh Gupta

Reputation: 2748

pattern Recognizer in java

I'm writing a file renamer program in java. The issue is when giving input pattern.

When the input is complex like (][) in that case, I'm getting errors by java.util.regex.Pattern class..

The major issue of writing this code is that the input pattern and replacement pattern are user input. How can I handle such characters during processing ???

Upvotes: 0

Views: 515

Answers (3)

Just Me
Just Me

Reputation: 11

They are reserved characters in regex you need to escape them with two backslashes

//]

OOPS too much Microsoft influence I meant

backslashes \\]

http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html

Upvotes: 0

JiP
JiP

Reputation: 3258

This is an example of how one can escape the special RegExp characters in the Java source code. I believe that you will have to escape the special characters manually if the pattern is being entered by a user.


package edu.mew.test.regexp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExpPatternTester {

  public static void main(String[] args) {
    String s1 = "filename()[].txt";
    Pattern p = Pattern.compile(".*\\(\\)\\[\\].*");
    Matcher m1 = p.matcher(s1);
    System.out.println(m1.matches());
    String s2 = "filename.txt";
    Matcher m2 = p.matcher(s2);
    System.out.println(m2.matches());
  }

}


Upvotes: 3

Mark Byers
Mark Byers

Reputation: 838116

You can escape special characters in a regular expression using Pattern.quote.

Upvotes: 2

Related Questions