-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressionValidator.java
More file actions
81 lines (67 loc) · 2.45 KB
/
ExpressionValidator.java
File metadata and controls
81 lines (67 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package taboola.israelrozen.solution_1;
import java.util.Scanner;
import java.util.regex.Pattern;
import taboola.israelrozen.solution_1.exceptions.InvalidExpressionException;
public class ExpressionValidator {
public boolean ValidExpression(String expr) {
Scanner scanner = new Scanner(expr);
boolean nextExpectedToken = false;
// first token has to be a variable
if (!scanner.hasNext() || !Pattern.matches("[a-z]", scanner.next()))
throw new InvalidExpressionException();
// second token has to be = / += assignment
if (scanner.hasNext()){
var nextToken=scanner.next();
if(!isAssignment(nextToken) && !isPlusEquelAssign(nextToken))
throw new InvalidExpressionException();
}else{
throw new InvalidExpressionException();
}
while (scanner.hasNext()) {
String token = scanner.next();
if (nextExpectedToken) { // next token has to be an Operation
if (!isOperation(token)) {
throw new UnsupportedOperationException();
}
nextExpectedToken = false;
} else {
//next token has to be a value
if (!isValue(token)) {
throw new InvalidExpressionException();
}
nextExpectedToken = true;
}
}
scanner.close();
return nextExpectedToken;
}
public boolean isAssignment(String s) {
return Pattern.matches("=", s);
}
public boolean isOperation(String s) {
return (Pattern.matches("\\+", s))
|| Pattern.matches("-", s)
|| Pattern.matches("\\*", s);
}
public boolean isValue(String s) {
return isNumber(s) || isVariable(s) || isPreIncrement(s) || isPostIncrement(s);
}
public boolean isNumber(String s) {
return Pattern.matches("[0-9]+", s);
}
public boolean isPlusEquelAssign(String s){
return Pattern.matches("\\+=", s);
}
public boolean isEquelAssign(String s){
return Pattern.matches("\\=", s);
}
public boolean isVariable(String s) {
return Pattern.matches("[a-z]", s);
}
public boolean isPreIncrement(String s) {
return Pattern.matches("\\+\\+[a-z]", s);
}
public boolean isPostIncrement(String s) {
return Pattern.matches("[a-z]\\+\\+", s);
}
}