There is a code section:

String[] del = {"\"", "\'", ",", ".", ";", "`", ":", "!", "(", ")", "<", ">", "-", "_"}; for (String delElement : del) { word = word.replaceAll(delElement, ""); } 

When compiling, throws a PatternSyntaxException exception:

 Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1 ( ^ at java.util.regex.Pattern.error(Pattern.java:1955) at java.util.regex.Pattern.accept(Pattern.java:1813) at java.util.regex.Pattern.group0(Pattern.java:2908) at java.util.regex.Pattern.sequence(Pattern.java:2051) at java.util.regex.Pattern.expr(Pattern.java:1996) at java.util.regex.Pattern.compile(Pattern.java:1696) at java.util.regex.Pattern.<init>(Pattern.java:1351) at java.util.regex.Pattern.compile(Pattern.java:1028) at java.lang.String.replaceAll(String.java:2223) at WordCounter.main(WordCounter.java:20) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) 

How can I fix it?

    2 answers 2

    Since the replaceAll method takes a regular expression as the first argument, it is ( perceived as a special character (as the beginning of a group, etc. ). Therefore, it must be escaped. The same applies ) . And more . in regular expressions means any character, therefore .replaceAll(".", "") results in an empty string as a result.

     String[] del = { "\"", "\'", ",", "\\.", ";", "`", ":", "!", "\\(", "\\)", "<", ">", "-", "_" }; String word = "abc\"',.;`:!()<>-_def"; for (String delElement : del) { word = word.replaceAll(delElement, ""); } System.out.println(word); 

    Since reg is used expression, it is possible to combine all elements for an exception into one expression, in order to make just one replaceAll . However, the readability of this option is not very different:

     String del = "[\"',\\.;`:!\\(\\)<>\\-_]"; String word = "abc\"',.;`:!()<>-_def"; word = word.replaceAll(del, ""); System.out.println(word); 
    • Why screening with two slashes, not one? - Evgeniy
    • one
      @Evgeniy record \\( leads to the fact that in fact the line will be stored \( . And this in the context of the reg. Of expressions just means "just a character (". - Regent

    Try this:

     String[] del = {"\"", "\'", ",", ".", ";", "`", ":", "!", "(", ")", "<", ">", "-", "_"}; for (String delElement : del) word = word.replaceAll(Pattern.quote(delElement), "");