split string based on comma delimiter - java

what is wrong in the following code?
String selectedCountriesStr = countries.replaceAll("[", "").replaceAll("]", "").trim();
String[] selectedCountriesArr = selectedCountriesStr.split(",");
Input String [10000,20000,304050,766666]
Getting error java.util.regex.PatternSyntaxException: Unclosed character class near index 0

You have to escape square brackets because replaceAll() interprets the first argument as a regular expression:
replaceAll("\\[", "")
^^
because, as the error message tells you, the are used for character classes in a regex. Double backslashes are necessary, because "\[" would be an invalid escape sequence. Since the backslash is escaped, the regex engine only receives one backslash.
Also, you can use
replace("[", "")
it will also replace all occurrences of the given CharSequence as is.
You can read more about it in JavaDoc.

Brackets are regex metacharacters, you need to prefix them with a backslash:
.replaceAll("\\[", "").replaceAll("\\]", "")
Also, since this is a simple string substitution, you'd better use .replace():
.replace("[", "").replace("]", "")

String str = "hi,hello,abc,example,problems";
String[] splits = str.split(",");
System.out.println("splits.size: " + splits.length);
for(String asset: splits){
System.out.println(asset);
}
Split function will easily split your string like this

Related

Splitting a String at last occurrence of slash

In java I can split at the last occurrence of a character (dot in this case) like this: String[] parts2 = path.split("\\.(?=[^.]*$)"); String Folderpath = parts2[0]; But when I try to split it at the last occurrence of a slash, like this: String[] parts2 = path.split("\\/(?=[^.]*$)"); String Folderpath = parts2[0]; it gives me following Warning: Redundant character escape '\/' in RegExp
Any help would be appreciated!
You're using the wrong tool for the job.
String folderPath = path.substring(0, path.lastIndexOf('/'));
But your actual problem is that '/' is not special in Java regular expression syntax and therefore does not need to be escaped with '\'. That's what the warning message is telling you. Delete the backslash that precedes '/'.

How do I make multi replace() java

I have a string with \r\n, \r, \n or \" characters in it. How can I replace them faster?
What I already have is:
String s = "Kerner\\r\\n kyky\\r hihi\\n \\\"";
System.out.println(s.replace("\\r\\n", "\n").replace("\\r", "").replace("\\n", "").replace("\\", ""));
But my code does not look beautiful enough.
I found on the Internet something like:
replace("\\r\\n|\\r|\\n|\\", "")
I tried that, but it didn't work.
You can wrap it in a method, put /r/n, /n and /r in a list. iterate the list and replace all such characters and return the modified string.
public String replaceMultipleSubstrings(String original, List<String> mylist){
String tmp = original;
for(String str: mylist){
tmp = tmp.replace(str, "");
}
return tmp;
}
Test:
mylist.add("\\r");
mylist.add("\\r\\n");
mylist.add("\\n");
mylist.add("\\"); // add back slash
System.out.println("original:" + s);
String x = new Main().replaceMultipleSubstrings(s, mylist);
System.out.println("modified:" + x);
Output:
original:Kerner\r\n kyky\r hihi\n \"
modified:Kerner kyky hihi "
I don't know if your current replacement logic be correct, but it says now that either \n, \r, or \r\n gets replaced with empty string, and backslash also gets replaced with empty string. If so, then you can try the following regex replace all:
String s = "Kerner\\r\\n kyky\\r hihi\\n \\\"";
System.out.println(s.replaceAll("\\r|\\n|\\r\\n|\\\\", ""));
One problem I saw with your attempt is that you are calling replace(), not replaceAll(), so it would only do a single replacement and then stop.
String.replaceAll() can be used, in your question you tried to use String.replace() which does not interpret regular expressions, only plain replacement strings...
You also need to escape the \\ again, i.e. \\\\ instead of \\
String s = "Kerner\\r\\n kyky\\r hihi\\n \\\"";
System.out.println(s.replaceAll("\\\\r|\\\\n|\\\\\"", ""));
Output
Kerner kyky hihi
Note the differences between String.replaceAll() and String.replace()
String.replaceAll()
Replaces each substring of this string that matches the given regular
expression with the given replacement.
String.replace()
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence.
Use a regular expression if you want to do all the replaces in one go.
http://www.javamex.com/tutorials/regular_expressions/search_replace.shtml

String.split not working with combination of delimiter {^

I am trying to split the string with combination of {^
How to use combination of delimiter for splitting the string.
The sample data is :
String str = "0002{^000000000000001157{^000006206210015461{^PR{^ID{^62499{^";
The delimiter passed to String.split() is a regex. As { and ^ are characters with special meaning within a regex, you need to escape them if you want to use them as literals:
String[] tokens = str.split("\\{\\^");
split method in java takes an regex as an input.
so if you want to split the string using '{' and '^' then you need to do the following:
String str = "0002{^000000000000001157{^000006206210015461{^PR{^ID{^62499{^";
String[] splitted = str.split("\\{\\^"); //note \\ before { and ^
You have to escape { and ^ in your split Statement, because both are Special character in regex:
s.split("\\{\\^");

Eliminating Unicode Characters and Escape Characters from String

I want to remove all Unicode Characters and Escape Characters like (\n, \t) etc. In short I want just alphanumeric string.
For example :
\u2029My Actual String\u2029
\nMy Actual String\n
I want to fetch just 'My Actual String'. Is there any way to do so, either by using a built in string method or a Regular Expression ?
Try
String stg = "\u2029My Actual String\u2029 \nMy Actual String";
Pattern pat = Pattern.compile("(?!(\\\\(u|U)\\w{4}|\\s))(\\w)+");
Matcher mat = pat.matcher(stg);
String out = "";
while(mat.find()){
out+=mat.group()+" ";
}
System.out.println(out);
The regex matches all things except unicode and escape characters. The regex pictorially represented as:
Output:
My Actual String My Actual String
Try this:
anyString = anyString.replaceAll("\\\\u\\d{4}|\\\\.", "");
to remove escaped characters. If you also want to remove all other special characters use this one:
anyString = anyString.replaceAll("\\\\u\\d{4}|\\\\.|[^a-zA-Z0-9\\s]", "");
(I guess you want to keep the whitespaces, if not remove \\s from the one above)

How to split the string using '^' this special character in java?

I want to split the following string "Good^Evening" i used split option it is not split the value. please help me.
This is what I've been trying:
String Val = "Good^Evening";
String[] valArray = Val.Split("^");
I'm assuming you did something like:
String[] parts = str.split("^");
That doesn't work because the argument to split is actually a regular expression, where ^ has a special meaning. Try this instead:
String[] parts = str.split("\\^");
The \\ is really equivalent to a single \ (the first \ is required as a Java escape sequence in string literals). It is then a special character in regular expressions which means "use the next character literally, don't interpret its special meaning".
The regex you should use is "\^" which you write as "\\^" as a Java String literal; i.e.
String[] parts = "Good^Evening".split("\\^");
The regex needs a '\' escape because the caret character ('^') is a meta-character in the regex language. The 2nd '\' escape is needed because '\' is an escape in a String literal.
try this
String str = "Good^Evening";
String newStr = str.replaceAll("[^]+", "");

Categories