I'm separating a string which is a mathematical expression, I want to split every number, operator and parentheses, and send them to an array, this is my code:
Scanner in = new Scanner(System.in);
System.out.println("enter the expression :");
String infija = in.nextLine();
String separate[] = infix.split("(?=[-+*/%()])|(?<=[^-+*/%][-+*/])|(?<=[()])");
but when I enter an expression with m modulus, the code does not separate it.
For example, entering
(2/3)+(2%1)
the expected result is:
[(,2, /, 3,), +,(, 2, %, 1,)]
There's an easier way:
String separate[] = infix.split("\\b|(?<=\\D)(?=\\D)");
This splits on word boundary and between non-digits.
In regex, a "word" char is any digit, letter or underscore. A word boundary is between a word char and a non-word char (and visa versa).
Test code:
System.out.println(Arrays.toString("2/(3+2)%1".split("\\b|(?<=\\D)(?=\\D)")));
output:
[2, /, (, 3, +, 2, ), %, 1]
This should do it,
String myString= "(2/3)+(2%1)";
String[] result = myString.split("(?<=[-+*/%()])|(?=[-+*/%()])");
System.out.println(Arrays.toString(result));
output:
[(, 2, /, 3, ), +, (, 2, %, 1, )]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.