separate mathematical expression in java - java

Would anyone be able to help me with separating this mathematical expression 125*1*4*4+82*1*10+2*59+2+4 in Java. I want to get the numbers form the expression, and I'm not sure how to use split() method over here.

You can use split with this regex [*+] :
String[] numbers = "125*1*4*4+82*1*10+2*59+2+4".split("[*+]");
Outputs
[125, 1, 4, 4, 82, 1, 10, 2, 59, 2, 4]
In case the mathematical expression contains spaces, you can remove them before and use split so you can use :
String[] numbers = "125*1*4*4+82*1*10+2*59+2+4".replaceAll("\\s+", "").split("[*+]");
//---------------------------------------------^----------------------^
Note you can add another arithmetic operators like [*+-/]
Another solution from eparvan:
In case you are not sure what the expression can contain you can use :
String[] numbers = "125*1*4*4+82*1*10+2*59+2+4".replaceAll("\\s+", "").split("[^0-9]");
//----------------------------------------------------------------------------^----^
Edit
What if I want to get the "+" and "*" ?
Input: 125*1*4*4+82*1*10+2*59+2+4 Output: ***+**+*++
In this case you can split with \d+ like this :
String[] numbers = "125*1*4*4+82*1*10+2*59+2+4".replaceAll("\\s+", "").split("\\d+");
But i will prefert to go with Pattern it is more practice then split for example you can use :
String str = "125*1/4*4+82*1*10+2/59-2+4";
String regex = "[^\\d]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}

Related

Regex to find a group which not match with given pattern?

I have a string say :
test=t1,test2=1,test3=t4
I want to find group or value where test2 value is not equal to 1,
I know I can find its value easily by using regex like .+,test2=(.+?),.+. but it also give me where test2=1, but I want test2 value only if it is not equal to one?
You can use negative lookahead assertion:
"test2=(?!1\\b)([^,]*)"
Above pattern will matchtest2 will match only if it is not followed by 1 (word boundary \b is used to not match numbers like 17, but only match 1)
This will work for you :
String s = "test=t1,test2=2,test3=t4";
Pattern p = Pattern.compile("test2=(?!1,)(\\d+)");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(1));
}
I/O :
"test=t1,test2=2,test3=t4" 2
"test=t1,test2=11,test3=t4" 11
"test=t1,test2=1,test3=t4" no result

How to split a String of numbers and chars, only by chars

i need to split a String into parts of number sequences and chars between them. Something like this:
input: "123+34/123(23*12)/100"
output[]:["123","+","34","/","123","(","23","*","12",")","/","100"]
Is this somehow possible, or is it possible to split a String by multiple chars? Otherwise, is it possible to loop through a String in Java?
You can use a regular expression.
String input = "123+34/123(23*12)/100";
Pattern pattern = Pattern.compile("\\d+|[\\+\\-\\/\\*\\(\\)]");
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
System.out.println(matcher.group());
}
Use a lookahead assertion based regex for splitting the input string.
String input = "123+34/123(23*12)/100";
System.out.println(Arrays.toString(input.split("(?<=[/)+*])\\B(?=[/)+*])|\\b")));
Output:
[123, +, 34, /, 123, (, 23, *, 12, ), /, 100]

Java: extract the single matching groups from a string with regular expression [duplicate]

This question already has answers here:
How to split a string between letters and digits (or between digits and letters)?
(8 answers)
Closed 8 years ago.
I have this kind of string: 16B66C116B or 222A3*C10B
It's a number (with unknow digits) followed or by a letter ("A") or by a star and a letter ("*A"). This patter is repeated 3 times.
I want to split this string to have: [number,text,number,text,number,text]
[16, B, 66, C, 116, B]
or
[16, B, 66, *C, 116, B]
I wrote this:
String tmp = "16B66C116B";
String tmp2 = "16B66*C116B";
String pattern = "(\\d+)(\\D{1,2})(\\d+)(\\D{1,2})(\\d+)(\\D{1,2})";
boolean q = tmp.matches(pattern);
String a[] = tmp.split(pattern);
the pattern match right, but the splitting doesn't work.
(I'm open to improve my pattern string, I think that it could be write better).
You are misunderstanding the functionality of split. Split will split the string on the occurence of the given regular expression, since your expression matches the whole string it returns an empty array.
What you want is to extract the single matching groups (the stuff in the brackets) from the match. To achieve this you have to use the Pattern and Matcher classes.
Here a code snippet which will print out all matches:
Pattern regex = Pattern.compile("(\\d+)(\\D{1,2})(\\d+)(\\D{1,2})(\\d+)(\\D{1,2})");
Matcher matcher = regex.matcher("16B66C116B");
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); ++i) {
System.out.println(matcher.group(i));
}
}
Of course you can improve the regular expression (like another user suggested)
(\\d+)([A-Z]+)(\\d+)(\\*?[A-Z]+)(\\d+)([A-Z]+)
Try with this pattern (\\d)+|(\\D)+ and use Matcher#find() to find the next subsequence of the input sequence that matches the pattern.
Add all of them in a List or finally convert it into array.
String tmp = "16B66C116B";
String tmp2 = "16B66*C116B";
String pattern = "((\\d)+|(\\D)+)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(tmp);
while (m.find()) {
System.out.println(m.group());
}

Regex - Match numbers & special cases

I'm trying to make a regex that would produce the following results :
for 7.0 + 5 - :asc + (8.256 - :b)^2 + :d/3 : 7.0, 5, :asc, 8.256, :b, 2, :d, 3
for -+*-/^^ )รง# : nothing
It's should first match numbers which can be float, so in my regex I have : [0-9]+(\\.[0-9])? but it should also mach special cases like :a or :Abc.
To be more precise, it should (if possible) match anything but mathematical operators /*+^- and parentheses.
So here is my final regex : ([0-9]+(\\.[0-9])?)|(:[a-zA-Z]+) but it's not working because matcher.groupCount() returns 3 for both of the examples I gave.
Groups are what you specifically group in the regex. Anything surrounded in parentheses is a group. (Hello) World has 1 group, Hello. What you need to be doing is finding all the matches.
In your code ([0-9]+(\\.[0-9])?)|(:[a-zA-Z]+), 3 sets of parentheses can be seen. This is why you will always be given 3 groups in every match.
Your code works fine as it is, here is an example:
String text = "7.0 + 5 - :asc + (8.256 - :b)^2 + :d/3";
Pattern p = Pattern.compile("([0-9]+(\\.[0-9]+)?)|(:[a-zA-Z]+)");
Matcher m = p.matcher(text);
List<String> matches = new ArrayList<String>();
while (m.find()) matches.add(m.group());
for (String match : matches) System.out.println(match);
The ArrayList matches will contain all of the matches that your regex finds.
The only change I made was add a + after the second [0-9].
Here is the output:
7.0
5
:asc
8.256
:b
2
:d
3
Here is some more information about groups in java.
Does that help?
Your regex is correct, run the following code:
String input = "7.0 + 5 - :asc + (8.256 - :b)^2 + :d/3"; // your input
String regex = "(\\d+(\\.\\d+)?)|(:[a-z-A-Z]+)"; // exactly yours.
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
Your problem is the understanding of the method matcher.groupCount(). JavaDoc clearly says
Returns the number of capturing groups in this matcher's pattern.
([^\()+\-*\s])+ //put any mathematical operator inside square bracket

java string split regular expression

I have a string (1, 2, 3, 4), and I want to parse the integers into an array.
I can use split(",\\s") to split all but the beginning and ending elements. My question is how can I modify it so the beginning and ending parenthesis will be ignored?
You'd be better served by matching the numbers instead of matching the space between them. Use
final Matcher m = Pattern.compile("\\d+").matcher("(1, 2, 3, 4)");
while (m.find()) System.out.println(Integer.parseInt(m.group()));
Use 2 regexes: first that removes parenthesis, second that splits:
Pattern p = Pattern.compile("\\((.*)\\)");
Matcher m = p.matcher(str);
if (m.find()) {
String[] elements = m.group(1).split("\\s*,\\s*");
}
And pay attention on my modification of your split regex. It is much more flexible and safer.
You could use substring() and then split(",")
String s = "(1,2,3,4)";
String s1 = s.substring(1, s.length()-2);//index should be 1 to length-2
System.out.println(s1);
String[] ss = s1.split(",");
for(String t : ss){
System.out.println(t);
}
Change it to use split("[^(),\\s]") instead.

Categories

Resources