I just started to learn about Regular Expression with Java. I have this project from hyperskill.com called "Smart Calculator" it is like the Python interpreter where you can input a arithmetic operation and when you press enter there is an output.
I would like to match if the input is valid like 2 + 2 - 3
and won't match if the input is 2 + 2 -
.
I have these regular expression (\s*[0-9]+\s*[\+\-\*\/]+\s*[0-9]+\s*){1,}
But when I tried to test with some inputs...
[In] 1 + 1
[Out] Matched
[In] 1 + 1 + 1 // Not matched
[Out] Not Matched
[In] 1 + 12 + 1 //But this one matched
[Out] Matched
[az]
is regexpese for: Any character between a and z. So, your [+-*/]
is regexpese for: "Any character having a unicode codepoint value between the codepoint value of +
and the codepoint value of *
which is problematic. Try putting the -
at the start or end, in which case it does mean literally the -
character, or escape it. So, make that: [-+*/]
.
Secondly, your regexp is for:
which you then state as: This, at least once or more (note that {1,}
is just a silly way of writing +
!
thus, you've set up the regexp to look for example for:
That duplication of 'a number' in the middle is your problem. The reason 1+12+1
matches is because your regexp matches that as 1+1
followed by 2+1
. That's also the reason why 1+1+1
does not match.
The solution is to start with a number, and then repeat only the 'operator, then number' part.
Note that \d
is short for digit, shorter than [0-9].
Finally, you've said that any number of operators is okay, which makes no sense. try it: 1++1
is valid according to your regex here.
Putting it all together:
\s*\d+(\s*[-+*/]\s*\d+)+
is all you need.
Use the regex, (\s*[0-9]+\s*([+-]+\s*[0-9]+\s*)*)
. Check this for an explanation of the regex.
public class Main {
public static void main(String[] args) {
String[] arr = { "1 + 1", "1 + 1 + 1", "2 + 2 - ", "2 + 2 - 3", "1 + 12 + 1" };
for (String s : arr) {
System.out.println(s + " => " + s.matches("(\\s*[0-9]+\\s*([+-]+\\s*[0-9]+\\s*)*)"));
}
}
}
Output:
1 + 1 => true
1 + 1 + 1 => true
2 + 2 - => false
2 + 2 - 3 => true
1 + 12 + 1 => true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.