Java: Split String around "+" [duplicate] - java

This question already has answers here:
Java - How to split a string on plus signs?
(2 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 4 years ago.
Just found out, that I get a NullPointerException when trying to split a String around +, but if I split around - or anything else (and change the String as well of course), it works just fine.
String string = "Strg+Q";
String[] parts = string.split("+");
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Q
Would love to hear from you guys, what I am doing wrong!
This one works:
String string = "Strg-Q";
String[] parts = string.split("-");
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Q

As + is one of the special regex syntaxes you need to escape it.
Use
String[] parts = string.split("\\+");
Instead of
String[] parts = string.split("+");

Try this:
final String string = "Strg+Q";
final String[] parts = string.split("\\+");
System.out.println(parts[0]); // Strg
System.out.println(parts[1]); // Q

It happens because + is a special character in Regex - it's the match-one-or-more quantifier.
The only thing you need to do is to escape it:
String[] parts = string.split("\\+");

String.split(...) expects a Regular Expression and the '+' is a special character. Try:
String string = "Strg+Q";
String[] parts = string.split("[+]");
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Q

+ is a special regex character which means that you need to escape it in order to use it as a normal character.
String[] parts = string.split("\\+");

The problem you got here is that "+" is a meta character in Java, so you need to "scape" it by using "\\+".

As others have mentioned, '+' is special when dealing with regex. In general, if a character is special you can use Pattern.quote() to escape it, as well as "\\+". Documentation on Pattern: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Example:
String string = "Strg-Q";
String[] parts = string.split(Pattern.quote("+"));
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Qenter code here
Remember to import pattern from java.util.regex!

Amit beat me too it. string.split() takes a regular expression as its argument. In regexes + is a special symbol. Escape it with a backslash. Then, since it's a java string, escape the backslash with another backslash, so you get \+. Try testing your regular expressions on an online regex tester.

Related

How to split a string if my string contains ^ symbol in java. I want to create an array out of it [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Split string with dot as delimiter
(13 answers)
Closed 2 years ago.
I have a string, which contains ^ symbol given below.
String tempName = "afds^afcu^e200f.pdf"
I want to split it like below
[afds, afcu, e200f]
How to resolve this.
The parameter to split() is a regular expression, which has special meta-characters. If the delimiter you're splitting on contains those special characters (e.g. ^), you have two options:
Escape the characters using \, which has to be doubled in a Java string literal to \\:
String[] result = tempName.split("\\^");
If you don't want to bother with that, or if the delimiter is dynamically assigned at runtime, so you can't escape the special characters yourself, call Pattern.quote() to do it for you:
String[] result = tempName.split(Pattern.quote("^"));
you need to add \\ in split method of String to split the string by this (^), because ^ is an special character in regular expression and you need to omit it with \\:
String tempName = "afds^afcu^e200f.pdf";
String [] result = tempName.split("\\^");
System.out.println(Arrays.toString(result));
Java characters that have to be escaped in regular expressions are:
.[]{}()<>*+-=!?^$|
Two of the closing brackets (] and }) are only need to be escaped after opening the same type of bracket.
In []-brackets some characters (like + and -) do sometimes work without escape.
more info...
String.split() in Java takes a regular expression. Since ^ is a control character in regex (when at the beginning of the regex string it means "the start of the line"), we need to escape it with a backslash. Since backslash is a control character in Java string literals, we also need to escape that with another backslash.
String tempName = "afds^afcu^e200f.pdf";
String[] parts = tempName.split("\\^");
You can use the retrieve a substring without the file extension and split that according to the delimiter that is required (^). This is shown below:
public static void main(String[] args) {
String tempName = "afds^afcu^e200f.pdf";
String withoutFileFormat = tempName.substring(0, tempName.length() - 4); //retrieve the string without the file format
String[] splitArray = withoutFileFormat.split("\\^"); //split it using the "^", use escape characters
System.out.println(Arrays.toString(splitArray)); //output the result
}
Required Output:
[afds, afcu, e200f]

JAVA: Replacing words in string

I want to replace words in a string, but I am having little difficulties. Here is what I want to do. I have string:
String a = "I want to replace some words in this string";
It should work like some kind of a translator. I am doing this with String.replaceAll(), but it doesn't work completely because of this. Let's say I am translating from English to German, than this should be the output (Ich means I in German).
String toTranslate = "I";
String translated = "Ich";
a = a.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
Now the output of the String a will be this:
"ich want to replace some words ich**n** **th**ich**s** **str**ich**ng**"
How to replace just the words, not the subwords in the words?
replaceAll uses regex, so you may add word boundaries or look-around mechanisms to check if there are no non-space characters surrounding word you want to replace.
String toTranslate = "I";
String translated = "Ich";
a = a.replaceAll("(?<!\\S)"+toTranslate.toLowerCase()+"(?!\\S)", translated.toLowerCase());
You can also add quotation mechanism to escape any regex metacharacters like + * ( inside word you want to replace. BTW you don't need to change your string to lower case, simply add case-insensitive flag to regex (?i).
a = a.replaceAll("(?i)(?<!\\S)"+Pattern.quote(toTranslate)+"(?!\\S)", translated.toLowerCase());
Use split(" ") for getting each word in the sentence. And then use replaceAll on each word.
String a = "I want to replace some words in this string";
String toTranslate = "I";
String translated = "Ich";
String newString[]=a.split(" ");
for (String string : newString) {
string=string.replaceAll(toTranslate, toTranslate.toLowerCase());//Adding this line ensures you dont miss any uppercase toTranslate
string=string.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
System.out.println("after translation ="+string);
}
String toTranslate = "I ";
String translated = "Ich ";
a = a.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
If you add a space after the "I" it should replace it when it comes to the word "Ich" but if your word ends in a "I" then thats another problem
If you assume that I will always be capitalized in English as it should be then
a = a.replaceAll(toTranslate, translated);
will work, otherwise you need to replace both cases
a = a.replaceAll(toTranslate, translated);
a = a.replaceAll("([^a-zA-Z])("+toTranslate.toLowerCase()+")([^a-zA-Z])", "$1"+translated.toLowerCase()+"$3");
Here is a working example
Yes, the word boundaries are the solution. I just did this in the regex:
text.replaceAll("\\b" + parts1[i] + "\\b", map.element.value);
Don't be confused with the second argument it's string (from Hash table).
You can use RegEx's word bound, which is \b
String toTranslate = "\\bI\\b";
String translated = "Ich";
a = a.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
This should ensure I is separated entirely into its own word
Edit: I misread the question and realized you want whole words. See above, as I have accounted for that

Split String with .(dot) character java android [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 5 years ago.
Hello friends i have string like
Android_a_b.pdf
i want to split it like Android_a_b and pdf
i try following code like
String s="Android_a_b.pdf";
String[] parts = s.split(".");
String part1 = parts[0];
String part2 = parts[1];
when i run above code it give me error like
11-05 09:42:28.922: E/AndroidRuntime(8722): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at String part1 = parts[0]; line
any idea how can i solve it?
You need to escape . using \
Eg:
String s="Android_a_b.pdf";
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
Now it will split by .
Split(regex) in Java
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
Keep in mind that
Parameters:
regex - the delimiting regular expression

How to Split String With double quotes in java [duplicate]

This question already has an answer here:
Divide/split a string on quotation marks
(1 answer)
Closed 8 years ago.
This question is Pretty Simple
How to Split String With double quotes in java?,
For example I am having string Do this at "2014-09-16 05:40:00.0",After Splitting, I want String like
Do this at
2014-09-16 05:40:00.0,
Any help how to achieve this?
This way you can escape inner double quotes.
String str = "Do this at \"2014-09-16 05:40:00.0\"";
String []splitterString=str.split("\"");
for (String s : splitterString) {
System.out.println(s);
}
Output
Do this at
2014-09-16 05:40:00.0
Use method String.split()
It returns an array of String, splitted by the character you specified.
public static void main(String[] args) {
String test = "Do this at \"2014-09-16 05:40:00.0\"";
String parts[] = test.split("\"");
String part0 = parts[0];
String part1 = parts[1];
System.out.println(part0);
System.out.println(part1);
}
output
Do this at
2014-09-16 05:40:00.0
Try this code. Maybe it can help
String str = "\"2014-09-16 05:40:00.0\"";
String[] splitted = str.split("\"");
System.out.println(splitted[1]);
The solutions provided thus far simply split the string based on any occurrence of double-quotes in the string. I offer a more advanced regex-based solution that splits only on the first double-quote that precedes a string of characters contained in double quotes:
String[] splitStrings =
"Do this at \"2014-09-16 05:40:00.0\"".split("(?=\"[^\"].*\")");
After this call, split[0] contains "Do this at " and split[1] contains "\"2014-09-16 05:40:00.0\"". I know you don't want the quotes around the second string, but they're easy to remove using substring.

use split() to split string like "004*034556"

In my project I used the code to split string like "004*034556" , code is like below :
String string = "004*034556";
String[] parts = string.split("*");
but it got some error and force closed !!
finally I found that if use "#" or another things its gonna work .
String string = "004#034556";
String[] parts = string.split("#");
how can I explain this ?!
Your forgetting something very trivial.
String string = "004*034556";
String[] parts = string.split("\\*");
I recommend you check out Escape Characters.
Use Pattern.quote to treat the * like the String * and not the Regex * (that have a special meaning):
String[] parts = string.split(Pattern.quote("*"));
See String#split:
public String[] split(String regex)
↑
Refer JavaDoc
String[] split(String regex)
Splits this string around matches of the given regular expression.
And the symbol "*" has a different meaning when we talk about Regex in Java
Thus you would have to use an escape character
String[] parts = string.split("\\*");

Categories

Resources