Java: String split acting weird - java

public String getPriceString() {
String priceString = "45.0";
String[] priceStringArray = priceString.split(".");
return priceStringArray.length + "";
}
Why does this give me a 0, zero? Shouldn't this be 2?

The argument to split() is a regular expression, and dot has a special meaning in regular expressions (it matches any character).
Try priceString.split("[.]");

You need to escape . like that
String[] priceStringArray = priceString.split("\\.");
split takes regular expression as a parameter and . means any character.
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum

escape . with backslash like \\.. . is a regex metacharacter for anything. you will have to escape it with \\. in order to make it treat as a normal character
String priceString = "45.0";
String[] priceStringArray = priceString.split("\\.");

String.split takes a regular expression pattern. You're passing in . which means you want to split on any character.
You could use "\\." as the pattern to split on - but personally I'd use Guava instead:
private static final Splitter DOT_SPLITTER = Splitter.on('.');
...
(If you're not already using Guava, you'll find loads of goodies in there.)

You need to escape . as \\. because . has special meaning in regex.
String priceString = "45.0";
String[] priceStringArray = priceString.split("\\.");
return priceStringArray.length + "";

Use String[] priceStringArray = priceString.split("\\.");
You will have to use escape sequence.

Related

Java String replaceAll() method using {} curly brackets

So for my app in Android Studio I want to replace the following:
String card = cards.get(count).getCard();
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("{Player1}", "Poep");
}
An example of String card can be: {Player1} switch drinks with the person next to you.
Somehow I can't use {} for the replacing. With the { it says: "Dangling metacharacter". Screenshot: https://prnt.sc/s2bbl8
Is there a solution for this?
the first Argument of replaceAll is a String that is parsed to a regalar Expression (regEx). The braces { } are special reserved meta characters to express something within the regular expression. To match them as normal characters, you need to escape them with a leading backslash \ and because the backslash is also a special character you need to escape itself with an additional backslash:
String replacedCard = card.replaceAll("\\{Player1\\}", "Poep");
Both { } are reserved regex characters. Since the replaceAll() function takes in a regex parameter, you have to explicitly state that { and } are part of your actual string. You can do this by prefixing them with the escape character: \. But because the escape character is also a reserved character, you need to escape it too.
Here's the correct way to write your code:
String card = cards.get(count).getCard();
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("\\{Player1\\}", "Poep");
}
You need to escape the initial { with \. I.e;
String card = "{Player1}";
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("\\{Player1}", "Poep");
System.out.println("replace: " + replacedCard);
}
The method String.replaceAll expects a regular expression. The other answers already give a solution for this. However, if you don't need regular expressions, then you can also use String.replace:
String replacedCard = card.replace("{Player1}", "Poep");
Since the input value of the replaceAll method expects a regex, you need to escape the curly brackets with a backslash. The curly brackets are special characters in the context of regular expressions.
In Java a backslash in a regex is accomplished by a double backslash \\ (see https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html for reference).
So you would need to adjust the line like so:
String replacedCard = card.replaceAll("\\{Player1\\}", "Poep");
{} are special characters for Regular Expressions. replaceAll method takes as first parameter a Regular Expressions, so if you want also to replace the curly brackets you have to skip them with \\ , as follow:
String card = cards.get(count).getCard();
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("\\{Player1}", "Poep");
}

Add escape "\" in front of special character for a string

I have a simple SQL query where I check whether the query matches any of the fields I have. I'm using LIKE statement for this. One of my field can have special characters and so does the search query. So I'm looking for a solution where I need to an escape "\" in front of the special character.
query = "hello+Search}query"
I need the above to change to
query = "hello\+Search\}query"
Is there a simple way of doing this other than searching for each special character separately and adding the "\". Because if I don't have the escape character I will get the error message
java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
Thanks in advance
Decide which special characters you want to escape and just call
query.replace("}", "\\}")
You may keep all special characters you allow in some array then iterate it and replace the occurrences as exemplified.
This method replaces all regex meta characters.
public String escapeMetaCharacters(String inputString){
final String[] metaCharacters = {"\\","^","$","{","}","[","]","(",")",".","*","+","?","|","<",">","-","&","%"};
for (int i = 0 ; i < metaCharacters.length ; i++){
if(inputString.contains(metaCharacters[i])){
inputString = inputString.replace(metaCharacters[i],"\\"+metaCharacters[i]);
}
}
return inputString;
}
You could use it as query=escapeMetaCharacters(query);
Don't think that any library you would find would do anything more than that. At best it defines a complete list of specialCharacters.
There is actually a better way of doing this in a sleek manner.
String REGEX = "[\\[+\\]+:{}^~?\\\\/()><=\"!]";
StringUtils.replaceAll(inputString, REGEX, "\\\\$0");
You need to use \\ to introduce a \ into a string literal; that is you need to escape the \. (A single backslash is used to introduce special characters into a string: e.g. \t is a tab.)
query = "hello\\+Search\\}query" is what you need.
I had to do same thing in javascript. I came up with below solution. I think it might help someone.
function escapeSpecialCharacters(s){
let arr = s.split('');
arr = arr.map(function(d){
return d.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\'+d)
});
let reg = new RegExp(arr.join(''));
return reg;
}
let newstring = escapeSpecialCharacters("hello+Search}query");
If you want to use Java 8+ and Streams, you could do something like:
private String escapeSpecialCharacters(String input) {
List<String> specialCharacters = Lists.newArrayList("\\","^","$","{","}","[","]","(",")",".","*","+","?","|","<",">","-","&","%");
return Arrays.stream(input.split("")).map((c) -> {
if (specialCharacters.contains(c)) return "\\" + c;
else return c;
}).collect(Collectors.joining());
}
The simple version ( without deprecated StringUtils.replaceAll ):
String regex = "[\\[+\\]+:{}^~?\\\\/()><=\"!]";
String query = "hello+Search}query";
String replaceAll = query.replaceAll(regex, "\\\\$0");

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("\\{\\^");

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("[^]+", "");

How to Replace dot (.) in a string in Java

I have a String called persons.name
I want to replace the DOT . with /*/ i.e my output will be persons/*/name
I tried this code:
String a="\\*\\";
str=xpath.replaceAll("\\.", a);
I am getting StringIndexOutOfBoundsException.
How do I replace the dot?
You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.
str=xpath.replaceAll("\\.", "/*/"); //replaces a literal . with /*/
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)
If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.
replace replaces each matching substring but does not interpret its argument as a regular expression.
str = xpath.replace(".", "/*/");
Use Apache Commons Lang:
String a= "\\*\\";
str = StringUtils.replace(xpath, ".", a);
or with standalone JDK:
String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);
return sentence.replaceAll("\s",".");

Categories