Results 1 to 3 of 3
  1. #1
    nenadm is offline Member
    Join Date
    Nov 2008
    Rep Power

    Default Filtering with Pattern, use metacharacters as a literal


    I am using java.util.regex.Pattern for searching data in my JTable.

    Here is piece of code:

    boolean matches = false;
    Pattern p = Pattern.compile(searchString + ".*", (Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));
    // match against comment text
    String test = "test";
    matches = p.matcher(test).matches();
    return matches;

    Everything works fine, except for metacharacters: [, $, ^, &, ...
    When i enter some of the metacharacters i got matches even there are
    no such character in test string "test".
    I know that i need some way to escape those characters but not sure how
    to do that. I tried to replace all characters in searchString like this:
    [ replaced with \[
    & replaced with \& and so on.
    But then when i enter [ for searching i got following exception:

    Exception occurred during event dispatching:
    [java] java.util.regex.PatternSyntaxException: Unclosed character class near index 4
    [java] [.*.*
    [java] ^
    [java] at java.util.regex.Pattern.error(Unknown Source)
    [java] at java.util.regex.Pattern.clazz(Unknown Source)
    [java] at java.util.regex.Pattern.sequence(Unknown Source)
    [java] at java.util.regex.Pattern.expr(Unknown Source)
    [java] at java.util.regex.Pattern.compile(Unknown Source)
    [java] at java.util.regex.Pattern.<init>(Unknown Source)
    [java] at java.util.regex.Pattern.compile(Unknown Source)

    Any help will be appreciated.

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Rep Power


    Escape them with an added slash
    Java Code:
    String string= "abcd[test]";
    string= string.replaceAll("[", "\\[");
    string= string.replaceAll("]", "\\]");
    Note you will remove all the power of using regular expression, in this case why not just use String.indexOf?

  3. #3
    nenadm is offline Member
    Join Date
    Nov 2008
    Rep Power

Similar Threads

  1. Replies: 3
    Last Post: 03-26-2010, 08:09 AM
  2. Regex - matching literal characters
    By racha0601 in forum Advanced Java
    Replies: 3
    Last Post: 04-07-2009, 11:25 PM
  3. using Delimiter with metacharacters
    By wntdaliv in forum New To Java
    Replies: 10
    Last Post: 12-02-2008, 07:42 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts