Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String pattern matching problem in Java

Tags:

In my program when I'm using

line.replaceAll("(", "_");

I got a RuntimeException:

 at java.util.regex.Pattern.error(Unknown Source)
 at java.util.regex.Pattern.accept(Unknown Source)
 at java.util.regex.Pattern.group0(Unknown Source)
 at java.util.regex.Pattern.sequence(Unknown Source)
 at java.util.regex.Pattern.expr(Unknown Source)
 at java.util.regex.Pattern.compile(Unknown Source)
 at java.util.regex.Pattern.<init>(Unknown Source)
 at java.util.regex.Pattern.compile(Unknown Source)
 at java.lang.String.replaceAll(Unknown Source)
 at Processing.processEarly(Processing.java:95)
 at Processing.main(Processing.java:34)

Is there any reason? How can we avoid it?

like image 879
Mahesh Gupta Avatar asked Jan 09 '10 11:01

Mahesh Gupta


People also ask

What is string matching problem with example?

The string matching problem is this: given a smaller string P (the pattern) that we want to find occurrences of in T . If P occurs in T at shift i then P[j] = T[i+j] for all valid indices i of P . For example, in the string "ABABABAC", the pattern string "BAB" occurs at shifts 1 and 3.

What is string pattern matching give some examples?

String Matching Algorithm is also called "String Searching Algorithm." This is a vital class of string algorithm is declared as "this is the method to find a place where one is several strings are found within the larger string." Given a text array, T [1.....n], of n character and a pattern array, P [1......

Which of the following algorithms are used for string and pattern matching problems?

Hashing-string matching algorithms: Rabin Karp Algorithm: It matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters.

Which algorithm is best for string matching?

The Karp-Rabin Algorithm.


2 Answers

The first argument to string.replaceAll is a regular expression, not just a string. The opening left bracket is a special character in a regex, so you must escape it:

line.replaceAll("\\(", "_");

Alternatively, since you are replacing a single character, you could use string.replace like so:

line.replace('(', '_');
like image 147
David M Avatar answered Oct 16 '22 20:10

David M


The error message above the stack trace is (somewhat) helpful:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1 ( ^

(That's what I get in Java 6.) It mentions "regex", "group", and the parenthesis. If you can't see this message, you should check how you're logging/catching/displaying exceptions. It could save you some trouble in the future.

like image 45
Ken Avatar answered Oct 16 '22 20:10

Ken