使用正则表达式拆分 java 字符串,然后存储到堆栈中
Split java string using regex then store into stack
我基于正则表达式拆分字符串的逻辑存在一些错误。目标是为 python 语法创建分词器。我写了四个简单的正则表达式;数字、浮点数、运算符和变量。我想将上面列出的四个正则表达式中的第一组提取到一个字符串中,然后将其推送到我的堆栈中。
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
现在,代码是 运行 无限..
这样做:
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;
}
我基于正则表达式拆分字符串的逻辑存在一些错误。目标是为 python 语法创建分词器。我写了四个简单的正则表达式;数字、浮点数、运算符和变量。我想将上面列出的四个正则表达式中的第一组提取到一个字符串中,然后将其推送到我的堆栈中。
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
现在,代码是 运行 无限..
这样做:
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;
}