Using split() with "|" character [duplicate] - java

This question already has answers here:
Why does String.split need pipe delimiter to be escaped?
(3 answers)
Closed 9 years ago.
Just a quick question:
String input = "sam|y|rutgers";
String[] splitInput = input.split("|");
System.out.println(Arrays.toString(splitInput));
Output:
[, s, a, m, |, y, |, r, u, t, g, e, r, s]
I would like to split at the pipe characters to get
[sam,y,rutgers]
Any idea what I'm doing wrong here?

Try with one of these
split("\\|")
split("[|]")
split(Pattern.quote("|"))
split("\\Q|\\E")
split method uses regex as parameter and in regex | means OR so your current expression means empty string or empty String.
If you want to make | simple literal you need to escape it. To do this you can
place \ before it in regex engine which in String will be written as "\\|".
use character class [...] to escape most of regex metacharacters like split("[|]")
or surround your special characters with \\Q and \\E which will make every character (regardless if it is special or not) simple literal. This solution is used in Pattern.quote("regex").

You may try this:
String[] str= input.split("\\|");
"|" is a special character(OR) so you need to escape that using a slash \\. As answered here An unescaped | is parsed as a regex meaning "empty string or empty string,"

\Q & \E are regex quotes.
String[] splitInput = input.split("\\Q|\\E");

You can do it by StringTokenizer
StringTokenizer st2 = new StringTokenizer(input , "|");
while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
default delimeter is " " space.
StringTokenizer st2 = new StringTokenizer(input );//it will split you String by `" "` space

Related

I can not use regex to replace text contain "\" character [duplicate]

This question already has answers here:
How to escape text for regular expression in Java?
(8 answers)
Closed 2 years ago.
I have a snippet
public static void main(String[] args) {
// replacement text
String replacement = "Not Set";
// text
String text = "Item A \\(XXX\\) Lock"; // text is "Item A\(XXX\)Lock"
String regex = "\\(XXX\\)"; // regex is "\(XXX\)"
// result text
String resultText = text.replaceAll(regex, replacement);
System.out.println("Result text: " + resultText);
}
resultText is "Item A \(XXX\) Lock" -> I can not replace "\(XXX\)" to "Not Set".
Please help me if you know about this problem.
The regex language has its own escape sequence on top of the Java string literal escape sequence. So to match a backslash, you need \\ in the regex and thus \\\\ in the Java string literal
In this case you could also use Pattern.quote
text.replaceAll(Pattern.quote(regex), Matcher.quoteReplacement(replacement));
The characters \, ( and ) all have a special meaning when used in a regular expression. But you don't want to use them with their special meaning, which means you have to escape them in the regular expression. That means preceding them with \, to tell the regular expression processor not to invoke the special meaning of those characters.
In other words, a regular expression containing \\ will match \, a regular expression containing
\( will match ( and so on.
To match \(XXX\), the regular expression you want will be \\\(XXX\\\) - see how there's an extra \ for each \, ( and ) that you want to match. But to specify this regular expression in a Java String literal, you need to write \\ in place of each \. That is, you need to write
"\\\\\\(XXX\\\\\\)". There are six \ characters in each little run of them.
String regex = "\\\\\\(XXX\\\\\\)";
String resultText = text.replaceAll(regex, replacement);

Getting " when trying to replace a character in string [duplicate]

This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
How do you match a caret (^) symbol in regex?
(2 answers)
Carets in Regular Expressions
(2 answers)
Closed 4 years ago.
I want to replace " from a string with ^.
String str = "hello \"there";
System.out.println(str);
String str1 = str.replaceAll("\"", "^");
System.out.println(str1);
String str2= str1.replaceAll("^", "\"");
System.out.println(str2);
and the output is :
hello "there
hello ^there
"hello ^there
why I am getting extra " in start of string and ^ in between string
I am expecting:
hello "there
the replaceAll() method consume a regex for the 1st argument.
the ^ in String str2= str1.replaceAll("^", "\""); will match the starting position within the string.
So if you want the ^ char, write \^
Hope this code can help:
String str2= str1.replaceAll("\\^", "\"");
Try using replace which doesnt use regex
String str2 = str1.replace("^", "\"");
^ means start of a line in regex, you can add two \ before it:
String str2= str1.replaceAll("\\^", "\"");
The first is used to escape for compiling, the second is used to escape for regex.
Since String::replaceAll consumes regular expression you need to convert your search and replacement strings into regular expressions first:
str.replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("^"));
Why do you want to use replaceAll. Is there any specific reason ?
If you can use replace function then try below
String str2= str1.replace("^", "\"");

String.split() not working with "[]" [duplicate]

This question already has answers here:
Why can't I split a string with the dollar sign?
(6 answers)
Closed 7 years ago.
I have a IPv6 string
String str = "demo1 26:11:d0a2:f020:0:0:0:a3:2123 demo2";
String searchString = "26:11:d0a2:f020:0:0:0:a3:2123";
When i use str.split(searchString) code returns
["demo1 ", " demo2"]
Which is fine but when i use:
String str = "demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2";
String searchString = "[26:11:d0a2:f020:0:0:0:a3]:2123";
and do str.split(searchString) it reutrns
[demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2]
Which is wrong i guess , can some one tell why I am getting this sort of output?
Since split function takes a regex as parameter, you need to escape those brackets otherwise this [26:11:d0a2:f020:0:0:0:a3] would match a single character only.
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
str.split(searchString);
It is happening because split(String str) take regex pattern string as argument. And that string will be used as regex pattern to match all the delimiter with this pattern.
In your regex pattern you are providing character sets in [].
To make it work your way you will have to use this regex pattern string :
\[26:11:d0a2:f020:0:0:0:a3\]:2123
i.e. in java :
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
I hope you are familiar with the string regexs. In java, the regex [abc] means match with a OR b OR c I encourage you to escape your square brackets try:
String str = "demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2";
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
You have to use an escape sequence for some special characters. Use \\[ ... \\] in the searchString variable.

Java String.split mehod don't work well [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Split string with | separator in java
I'm little confused as when i do the following:
String example1 = "Hello|World";
String[] splitRes;
splitRes = example1.split("|");
I don't get split string
Hello index 0
World index 1
But if I'll do
String example1 = "Hello:World";
String[] splitRes;
splitRes = example1.split(":");
then it works..
Why is it happening?
split uses a regex, you must escape the pipe because it is a "or" operator in regex:
example1.split("\\|");
String.split() expects regular expression as argument, | is a meta character "OR" in regular expression. You have to escape with \ (so it becomes \|). Note that in Java string, you have to write it as \\ since \ is also an escape character in Java string.
| is used in regular expression, .split also use regular expression so you need to escape it.
String str = ""Hello:World"; ";
String[] temp;
String delimiter = "\\|";
SepString= str.split(delimiter);
/* print test */
for(int i =0; i < SepString.length ; i++)
System.out.println(SepString[i]);
Split takes a regexp as an argument, | is a a regexp symbol.
You would have to escape it using \ which in a java string is two of them: \\
.split("\\|");

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