This question has already been answered:

Hello.
Tell me, please, a suitable regular expression in java to divide the string containing the arithmetic expression into numbers (double) and operations.

For example, after converting the string "15.21 * 6.3", you should get an array of three values "15.21" , "*" and "6.3" .

An example that works for integer:

String input = "4+7"; String[] split = input.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)))"); 

Result:

 split[0] = "4"; split[1] = "+"; split[2]="7"; 

To get something similar for double has not yet succeeded.
thank

Reported as a duplicate by members aleksandr barakin , VenZell , Pavel Mayorov , Grundy , insolor 4 May '16 at 1:17 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 2
    In my opinion, it will be easier to just go through the line and look for signs of operations, and everything between them is taken as numbers. - AivanF.
  • Perhaps you `re right. But then the methods of processing the values ​​cut from the string are further complicated. Actually for this reason I try to get regex. - Egor
  • Why is it so complicated? I have written a lot of parsers of different languages ​​in different languages, everything works fine :) Do you want an example? - AivanF.
  • and now some classic LR parser will appear ... - pavel
  • five
    Search? ru.stackoverflow.com/questions/514535/… - Sergey Mitrofanov

2 answers 2

I hope someone will help. In my case it turned out with the following variant of the regular expression:

 String input1 = "48.50+50.20"; String input2 = "48.50*50.20"; String input3 = "48.50-50.20"; String input4 = "48.50/50.20"; String[] splitted = input.split("(?<=\\d)(?=(\\+|\\-|\\*|/))|(?<=(\\+|\\-|\\*|/))(?=\\d)"); 
  • (?<=\\d)(?=[-+*/])|(?<=[-+*/])(?=\\d) so the regular expression looks more natural, I recommend to simplify the expression in the answer, so it will help someone more effectively. - ReinRaus

I do not write in Java, but it is unlikely that it will be difficult for you to translate from C-like pseudocode.

 void processLine(string line) { // список для чисел List<double> numbers = new List<double>(); // список для символов операций между ними List<char> signs = new List<char>(); string temp = ""; char t; for (int i = 0; i < line.Length(); i++) { t = line[i]; switch (t) { // если знак операции case '+': case '-': case '*': case '/': { if (temp == "") { // ошибка, такого быть не должно } // обработать прошлую последовательность // символов как число numbers.Add((double)temp); // очистить сохранённую последовательность temp = ""; // и добавить сам знак signs.Add(t); } break; default: { // сохранить знак числа temp = temp + t; } } } // после последнего знака у нас должно быть // есть ещё одно число if (temp == "") { // тоже ошибка } numbers.Add((double)temp); //TODO: списки чисел и операций между ними получены, // обрабатывайте на здоровье // обратите внимание, что количество элементов в // numbers = кол-во эл-в в signs + 1 } 
  • Translate - no problem. Thank you very much for the option. I'll try to fasten something similar, if the regulars fail. The only argument why I'm trying is two lines of code against a separate method. Thanks again - Egor