Results 1 to 3 of 3
- 02-04-2011, 06:58 PM #1
Member
- Join Date
- Nov 2008
- Posts
- 19
- Rep Power
- 0
Filtering with Pattern, use metacharacters as a literal
Hello,
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.
- 02-04-2011, 08:21 PM #2
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,605
- Rep Power
- 5
Escape them with an added slash
Note you will remove all the power of using regular expression, in this case why not just use String.indexOf?Java Code:String string= "abcd[test]"; string= string.replaceAll("[", "\\["); string= string.replaceAll("]", "\\]");
- 02-04-2011, 10:10 PM #3
Member
- Join Date
- Nov 2008
- Posts
- 19
- Rep Power
- 0
Similar Threads
-
What is the difference between Inline literal and Static final String in Java.
By devaru2003 in forum Advanced JavaReplies: 3Last Post: 03-26-2010, 07:09 AM -
Regex - matching literal characters
By racha0601 in forum Advanced JavaReplies: 3Last Post: 04-07-2009, 11:25 PM -
using Delimiter with metacharacters
By wntdaliv in forum New To JavaReplies: 10Last Post: 12-02-2008, 06:42 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks