No question about SO concerns my specific issue. I don't know much about regex. I am creating an expression parser in Java using the Regex class for this purpose. I want to extract operands, arguments, operators, characters and function names from an expression, and then store it in an ArrayList. I am currently using this logic
String string = "2!+atan2(3+9,2+3)-2*PI+3/3-9-12%3*sin(9-9)+(2+6/2)" //This is just for testing purpose later on it will be provided by user List<String> res = new ArrayList<>(); Pattern pattern = Pattern.compile((\\Q^\\E|\\Q/\\E|\\Q-\\E|\\Q-\\E|\\Q+\\E|\\Q*\\E|\\Q)\\E|\\Q)\\E|\\Q(\\E|\\Q(\\E|\\Q%\\E|\\Q!\\E)) //This string was build in a function where operator names were provided. Its mean that user can add custom operators and custom functions Matcher m = pattern.matcher(string); int pos = 0; while (m.find()) { if (pos != m.start()) { res.add(string.substring(pos, m.start())) } res.add(m.group()) pos = m.end(); } if (pos != string.length()) { addToTokens(res, string.substring(pos)); } for(String s : res) { System.out.println(s); }
Output:
2 ! + atan2 ( 3 + 9 , 2 + 3 ) - 2 * PI + 3 / 3 - 9 - 12 % 3 * sin ( 9 - 9 ) + ( 2 + 6 / 2 )
The problem is that now the expression may contain a matrix with a custom format. I want to consider each Matrix as an Operand or Argument in the case of functions.
Input 1:
String input_1 = "2+3-9*[{2+3,2,6},{7,2+3,2+3i}]+9*6"
The output should be:
2 + 3 - 9 * [{2+3,2,6},{7,2+3,2+3i}] + 9 * 6
Input 2:
String input_2 = "{[2,5][9/8,func(2+3)]}+9*8/5"
The output should be:
{[2,5][9/8,func(2+3)]} + 9 * 8 / 5
Input 3:
String input_3 = "<[2,9,2.36][2,3,2!]>*<[2,3,9][23+9*8/8,2,3]>"
The output should be:
<[2,9,2.36][2,3,2!]> * <[2,3,9][23+9*8/8,2,3]>
I want the ArrayList to now contain every operand, operators, arguments, functions and characters for each index. How can I achieve the desired result using a regular expression. Expression validation is not required.