How to split a java string with "("? [duplicate] - java

This question already has answers here:
Groovy/Java split string on parentheses "("
(5 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 3 years ago.
I am trying to split a java string with the character "(".
For example :
split("wer(sde")= "wer"+"sde".
But it give exception. Is there a way to split this string using split() function without changing the character "(" to some other character.
String[] cp=cmd.split("{");
Output:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition

The thing is, split() receives as parameter a regular expression. Both {} and () are meta-characters and have a special meaning in a regex, so you need to escape them like this:
String[] cp = cmd.split("\\(|\\)");

The method split of String accept a String, that parameter is a regex :
public String[] split(String regex)
Splits this string around matches of the given regular expression.
Since ( is a reserved character in regex, you need to escape it \(.
But in Java, you need to escape twice \\(, once for the String and the second for the regex
This gives :
s.split("\\(");

Parentheses mean something in RegEx, they're used to group characters together. As such, if you intend to reference the literal character, '(' you must escape it within the RegEx:
String[] cp = cmd.split("\\(");
Note the use of two backslashes. This is because the JVM will also interpret a backslash as a metacharacter for escape purposes, so you must escape the backslash itself with another backslash in order for it to make it into the RegEx.

Related

Using Regex for splitting a string in java [duplicate]

This question already has answers here:
Why does this Java regex cause "illegal escape character" errors?
(7 answers)
Closed 3 years ago.
I want to split a string in java with white spaces. I know that the below line of code does it.
String s[] = str.split("\\\s+");
Here split function takes the regex by which the string must be split. So when I want to split string str through one or more spaces, I should pass \s+ as regex, then why is \\\s+ used?
This will do the split
String s[] = n.split("\\s+");
You don't need a third slash'\' - you get Compile Error.
And first '\' is for escaping the second '\'. Used as an escape character for '\s'.
Like Ismail said, you don't need the third backslash.
In your regex you want to use \s so in Java you also need to escape your backslashes for your tags.
Solution:
Why does this Java regex cause "illegal escape character" errors?

Why does split(".") fail? java [duplicate]

This question already has answers here:
Java RegEx meta character (.) and ordinary dot?
(9 answers)
Closed 8 years ago.
I've written the following code:
String[] arr = ((String) "asd.asd").split(".");
and arr=[]. Why?
split takes a regular expression as an argument. "." in regular means "any character".
Instead, use:
String[] arr = "asd.asd".split("\\.");
The backslashes escape the special meaning of the "." character in a regular expression.
http://docs.oracle.com/javase/tutorial/essential/regex/
split() accepts a regex. you should escape the . use "\\." . In regex . is a special character (Meta character) which means match any character.
You must double escape the ., otherwise the regular expression represents it as "any character".
Also, you don't need to cast "asd.asd" as String.
String[] arr = "asd.asd".split("\\.");
Because '.' is a special character. You need to escape it by writing it like this '\\.'

Java Regular Expression how to split special characters [duplicate]

This question already has answers here:
Replace special character with an escape preceded special character in Java
(4 answers)
Closed 8 years ago.
In java Regex i want to replace all the special characters to escape sequence.how can i do.
Example ::
//special chars ex "dd[u]i.* " to "dd//[u//]i//.//*"
To escape all special regexp control characters this method can be used:
Matcher.quoteReplacement(String s)
It returns a regular expression that matches exact s.
This comes from the javadoc:
Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ('\') and dollar signs ('$') will be given no special meaning.
To split or treat special characters in java pattern as normal one. You have to backshlas it.
\\.; \\* it might be treat now as '.' and '*'.

split() function for '$' not working [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 8 years ago.
I'm doing a simple code
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.split("$").length;i++){
System.out.println("I GOT IS :: "+splitString.split("$")[i]);
}
When I split like
splitString.split("$")
It is giving me output [122$23$56$rt]
Why this is not splinting on '$'?
String.split() takes in regex as argument and $ is a metacharacter in Java regex API. Therefore, you need to escape it:
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.split("\\$").length;i++){
System.out.println("I GOT IS :: "+splitString.split("\\$")[i]);
}
Other metacharacters supported by the Java regex API are: <([{\^-=!|]})?*+.>
split(Pattern.quote("$"))
Is my favorite.
See Pattern#quote:
Returns a literal pattern String for the specified String.
Your code doesn't work because $ has a special meaning in regex, and since String#split takes a regex as an argument, the $ is not interpreted as the String "$", but as the special meta character $.
Escape it. the split() method takes a regex: split("\\$")
try something like this
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.split("\\$").length;i++){
System.out.println("I GOT IS :: "+splitString.split("$")[i]);
}
NOTE: split() uses a regular expression.
Your regular expression uses a special character ie $
$ is the regular expression for "end of line".
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.length;i++){
System.out.println("Now you GOT this :: "+split(Pattern.quote("$")));
}
There are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".
So your $ is also metacharacter as defination says so you can't split using simple function. Though you must use pattern in this case.
Thanks..
Escape it like
split("\\$")
instead of split("$")
It will not work because split() takes input as RegEx
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.split("\\$").length;i++){
System.out.println("I GOT IS :: "+splitString.split("\\$")[i]);
}
String.split(), .match(), .replaceAll() are some of the methods that use RegEx pattern and so you should look at the javadoc of the Pattern class:
If your splitting character happen to be one of the pattern characters, you must escape it with \\, in this case your split call should be: .split("\\$")

Why can't I replace ":)" [duplicate]

This question already has answers here:
How to replace brackets in strings
(4 answers)
Closed 8 years ago.
I can't seem to replace a string of ":)" to something else, here is my code:
if(message.contains(":)")) message = message.replaceAll(":)", replacement);
This is the error:
Exception in thread "Listen" java.util.regex.PatternSyntaxException: Unmatched closing ')'
near index 0
:)
^
What should I do?
Don't use replaceAll(); use replace() when you want to replace literal strings:
message.replace(":)", replacement)
replaceAll() deals with regular expressions, in which ) has a special meaning, hence the error.
You must escape ) in regexen:
message = message.replaceAll(":\\)", replacement);
This is because ) has special meaning (capture groups), so you have to "tell" regex that you just want a literal ).
Write:
message.replaceAll(Pattern.quote(":)"), replacement);
String#replaceAll accept a regex, not a regular String. ) has a special meaning in regex, using quote will cause treating :) as the String :) and not the regex.
If you don't want to use Pattern#quote, you should escape the ) by \\. Note that escaping a regex is done by \, but in Java, \ is written as \\.
If you don't like any of the mentioned, use String#replace that doesn't accept a regex, and you're fine.

Categories

Resources