Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

java - regex for simple math equation

I want to recognize integers or decimals and the four simple operations, broken into tokens I can't get the decimal to work, can you please help?

My reg is

expression = "2.7 + 3 * (1 + 2)";
String expRegString = "\d+(\.\d+)*|[\(\)\+\-\*\/]";
Pattern expPattern = Pattern.compile(expRegString);
Matcher expMatcher = expPattern.matcher(expression);

while (expMatcher.find()){
    System.out.println(expMatcher.group());
}

gives me "+", "3", "(" , "1", "+" , "2",")"

Edit: the correct result would be "2.7","+", "3", "(" , "1", "+" , "2",")"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try removing all spaces and then split your data on every place that is before or after characters - + * / ( ).

This should do the trick

String expression = "2.7 + 3 * (1 + 2)";
String[] tokens = expression.replaceAll("\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])");

for (String token : tokens)
    System.out.println(token);

Output

2.7
+
3
*
(
1
+
2
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...