My input string looks like this "10^-9". Since Java don't handle exponentiation and "^" stands for bitwise XOR, I tried to do it differently. I splitted the String in 10 and -9 and parsed it into double, then used Math.pow() to get the value of it. The code looks like this:
String[] relFactorA = vA.getValue().split("^"); //vA.getValue is a String like `"10^-9"` or any other number instead of 9.
Double pow1 = Double.parseDouble(relFactorA[0]);
Double pow2 = Double.parseDouble(relFactorA[1]);
Double relFactor = Math.pow(pow1, pow2);
System.out.println(relFactor);
But that approach results in an java.lang.NumberFormatException. In the code I cannot find an error, whether I did something wrong or the compiler recognizes the "-(Minus)" as a "-(hyphen)", but I dont think thats the reason, because both Strings look the same and the compiler should see this.
You probably didn't split on ^ since split uses regex as parameter and in regex ^ has special meaning (its start of line). To make it literal use "\\^".
String.split() uses a regex as parameter. If you want to split for the symbol ^ use \\^ instead.
String[] relFactorA = vA.getValue().split("\\^");
Note that String#split takes a regex and not a String:
public String[] split(String regex)
You should escape the special character ^:
vA.getValue().split("\\^");
Escaping a regex is usually done by \, but in Java, \ is represented as \\.
Instead, you can use Pattern#quote that will treat the ^ as the String ^ and not the meta-character ^:
Returns a literal pattern String for the specified String.
vA.getValue().split(Patter.quote("^"));
Related
if (url.contains("|##|")) {
Log.e("url data", "" + url);
final String s[] = url.split("\\|##|");
}
I have a URL with the separator "|##|"
I tried to separate this but didn't find solution.
Use Pattern.quote, it'll do the work for you:
Returns a literal pattern String for the specified String.
final String s[] = url.split(Pattern.quote("|##|"));
Now "|##|" is treated as the string literal "|##|" and not the regex "|##|". The problem is that you're not escaping the second pipe, it has a special meaning in regex.
An alternative solution (as suggested by #kocko), is escaping* the special characters manually:
final String s[] = url.split("\\|##\\|");
* Escaping a special character is done by \, but in Java \ is represented as \\
You have to escape the second |, as it is a regex operator:
final String s[] = url.split("\\|##\\|");
You should try to understand the concept as well - String.split(String regex) interprets the parameter as a regular expression, and since pipe character "|" is a logical OR in regular expression, you would be getting result as an array of each alphabet is your word.
Even if you had used url.split("|"); you would have got same result.
Now why the String.contains(CharSequence s) passed the |##| in the start because it interprets the parameter as CharSequence and not a regular expression.
Bottom line: Check the API that how the particular method interprets the passed input. Like we have seen, in case of split() it interprets as regular expression while in case of contains() it interprets as character sequence.
You can check the regular expression constructs over here - http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
import java.util.StringTokenizer;
class MySplit
{
public static void main(String S[])
{
String settings = "12312$12121";
StringTokenizer splitedArray = new StringTokenizer(settings,"$");
String splitedArray1[] = settings.split("$");
System.out.println(splitedArray1[0]);
while(splitedArray.hasMoreElements())
System.out.println(splitedArray.nextToken().toString());
}
}
In above example if i am splitting string using $, then it is not working fine and if i am splitting with other symbol then it is working fine.
Why it is, if it support only regex expression then why it is working fine for :, ,, ; etc symbols.
$ 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 $. One sexy solution is:
settings.split(Pattern.quote("$"))
Pattern#quote:
Returns a literal pattern String for the specified String.
... The other solution would be escaping $, by adding \\:
settings.split("\\$")
Important note: It's extremely important to check that you actually got element(s) in the resulted array.
When you do splitedArray1[0], you could get ArrayIndexOutOfBoundsException if there's no $ symbol. I would add:
if (splitedArray1.length == 0) {
// return or do whatever you want
// except accessing the array
}
If you take a look at the Java docs you could see that the split method take a regex as parameter, so you have to write a regular expression not a simple character.
In regex $ has a specific meaning, so you have to escape it this way:
settings.split("\\$");
The problem is that the split(String str) method expects str to be a valid regular expression. The characters you have mentioned are special characters in regular expression syntax and thus perform a special operation.
To make the regular expression engine take them literally, you would need to escape them like so:
.split("\\$")
Thus given this:
String str = "This is 1st string.$This is the second string";
for(String string : str.split("\\$"))
System.out.println(string);
You end up with this:
This is 1st string.
This is the second strin
Dollar symbol $ is a special character in Java regex. You have to escape it so as to get it working like this:
settings.split("\\$");
From the String.split docs:
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.
On a side note:
Have a look at the Pattern class which will give you an idea as to which all characters you need to escape.
Because $ is a special character used in Regular Expressions which indicate the beginning of an expression.
You should escape it using the escape sequence \$ and in case of Java it should be \$
Hope that helps.
Cheers
I want to split a string when following of the symbols encounter "+,-,*,/,="
I am using split function but this function can take only one argument.Moreover it is not working on "+".
I am using following code:-
Stringname.split("Symbol");
Thanks.
String.split takes a regular expression as argument.
This means you can alternate whatever symbol or text abstraction in one parameter in order to split your String.
See documentation here.
Here's an example in your case:
String toSplit = "a+b-c*d/e=f";
String[] splitted = toSplit.split("[-+*/=]");
for (String split: splitted) {
System.out.println(split);
}
Output:
a
b
c
d
e
f
Notes:
Reserved characters for Patterns must be double-escaped with \\. Edit: Not needed here.
The [] brackets in the pattern indicate a character class.
More on Patterns here.
You can use a regular expression:
String[] tokens = input.split("[+*/=-]");
Note: - should be placed in first or last position to make sure it is not considered as a range separator.
You need Regular Expression. Addionaly you need the regex OR operator:
String[]tokens = Stringname.split("\\+|\\-|\\*|\\/|\\=");
For that, you need to use an appropriate regex statement. Most of the symbols you listed are reserved in regex, so you'll have to escape them with \.
A very baseline expression would be \+|\-|\\|\*|\=. Relatively easy to understand, each symbol you want is escaped with \, and each symbol is separated by the | (or) symbol. If, for example, you wanted to add ^ as well, all you would need to do is append |\^ to that statement.
For testing and quick expressions, I like to use www.regexpal.com
I need to cut certain strings for an algorithm I am making. I am using substring() but it gets too complicated with it and actually doesn't work correctly. I found this topic how to cut string with two regular expression "_" and "."
and decided to try with split() but it always gives me
java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^
So this is the code I have:
String[] result = "234*(4-5)+56".split("+");
/*for(int i=0; i<result.length; i++)
{
System.out.println(result[i]);
}*/
Arrays.toString(result);
Any ideas why I get this irritating exception ?
P.S. If I fix this I will post you the algorithm for cutting and then the algorithm for the whole calculator (because I am building a calculator). It is gonna be a really badass calculator, I promise :P
+ in regex has a special meaning. to be treated as a normal character, you should escape it with backslash.
String[] result = "234*(4-5)+56".split("\\+");
Below are the metacharaters in regex. to treat any of them as normal characters you should escape them with backslash
<([{\^-=$!|]})?*+.>
refer here about how characters work in regex.
The plus + symbol has meaning in regular expression, which is how split parses it's parameter. You'll need to regex-escape the plus character.
.split("\\+");
You should split your string like this: -
String[] result = "234*(4-5)+56".split("[+]");
Since, String.split takes a regex as delimiter, and + is a meta-character in regex, which means match 1 or more repetition, so it's an error to use it bare in regex.
You can use it in character class to match + literal. Because in character class, meta-characters and all other characters loose their special meaning. Only hiephen(-) has a special meaning in it, which means a range.
+ is a regex quantifier (meaning one or more of) so needs to be escaped in the split method:
String[] result = "234*(4-5)+56".split("\\+");
In Java, I am trying to split on the ^ character, but it is failing to recognize it. Escaping \^ throws code error.
Is this a special character or do I need to do something else to get it to recognize it?
String splitChr = "^";
String[] fmgStrng = aryToSplit.split(splitChr);
The ^ is a special character in Java regex - it means "match the beginning" of an input.
You will need to escape it with "\\^". The double slash is needed to escape the \, otherwise Java's compiler will think you're attempting to use a special \^ sequence in a string, similar to \n for newlines.
\^ is not a special escape sequence though, so you will get compiler errors.
In short, use "\\^".
The ^ matches the start of string. You need to escape it, but in this case you need to escape it so that the regular expression parser understands which means escaping the escape, so:
String splitChr = "\\^";
...
should get you what you want.
String.split() accepts a regex. The ^ sign is a special symbol denoting the beginning of the input sequence. You need to escape it to make it work. You were right trying to escape it with \ but it's a special character to escape things in Java strings so you need to escape the escape character with another \. It will give you:
\\^
use "\\^". Use this example as a guide:
String aryToSplit = "word1^word2";
String splitChr = "\\^";
String[] fmgStrng = aryToSplit.split(splitChr);
System.out.println(fmgStrng[0]+","+fmgStrng[1]);
It should print "word1,word2", effectively splitting the string using "\\^". The first slash is used to escape the second slash. If there were no double slash, Java would think ^ was an escape character, like the newline "\n"
None of the above answers makes no sense. Here is the right explanation.
As we all know, ^ doesn't need to be escaped in Java String.
As ^ is special charectar in RegulalExpression , it expects you to pass in \^
How do we make string \^ in java? Like this String splitstr = "\\^";