Home Error when use method String.replaceAll
Reply: 2

Error when use method String.replaceAll

no name
1#
no name Published in 2018-01-13 02:14:14Z

I use this code to get a string from JTextArea, then replace string by string from the string I got it from JTextArea.

String data = MainTextArea.getText().toString();
data = data.replaceAll("(", "<");
MainTextArea.setText(data);

I got an error in the second line of this code which says:

Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unclosed group near index 1

What should I do to solve this?

I don't know if there is more information should be provided to the question to be clear.

Update :

I am using a HashMap<string,string> to replace many strings this strings may contains some chars like "(" which needs the \ before it how to know that this string need those \ when i use this part of code

for (Map.Entry<String, String> entry : settingfile.CharactersMap.entrySet()) {
    System.out.println(entry.getKey() + " | " + entry.getValue());
    data = data.replaceAll(entry.getKey(), entry.getValue());
}
Aniket Sahrawat
2#
Aniket Sahrawat Reply to 2018-01-13 02:22:08Z

You need to escape ( using \\. Try this:

data = data.replaceAll("\\(", "<");

Docs for replaceAll()

As pointed by Jon Skeet, it would be simple to use replace:

data = data.replace('(', '<');
Jacek Cz
3#
Jacek Cz Reply to 2018-01-13 08:13:10Z

Diferent method from this family public String replace(char oldChar, char newChar) doesnt take regex machinery.

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)

So Your code can be

data = data.replace('(', '<');

Hope, non-regex version has better performance too

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.315373 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO