Split java string using regex then store into stack

Bimal Dahal :

There is some error in my logic for splitting string based on regex. The goal is create a tokenizer for the python syntax. I have four simple regex written; digits, floats, operators, and variables. I want to extract the first set of the four regex listed above into a string and then push it to my stack.

String s = "123+abc+123abc";
String allRegex = String.format("%s|%s|%s|%s", digit, floats, operators, variable);
Pattern allRegexPattern = Pattern.compile(allRegex);
Matcher matchString = allRegexPattern.matcher(s);

int group = 1;
while (s != null)
{
    if (group == 5)
        group = 1;
    if (matchString.find())
    {
        String temp = matchString.group(group);
        if (temp != null)
        {
            tokens.add(temp);
            s = s.replace(temp, "");
        }
        else
            group++;

    }
}

//Expecting ["123","+","abc","+","123abc"] in my stack

Right now, the code is running infinitely..

raviiii1 :

This will do:

public Stack<String> getStack(String expression){
    Stack<String> stack = new Stack<>();
    Pattern pattern = Pattern.compile("[0-9a-z]+|\\+|\\*");
    Matcher matcher = pattern.matcher(expression);
    while(matcher.find()) {
       stack.push(matcher.group());
    }
    System.out.println(stack.toString());
    return stack;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=158196&siteId=1