I would use a regex instead of having array of all the operators. Also, make sure the operators are in the exact order in your regex, i.e., <=
should be before <
, similarly, ==
should be before =
:
String regex = "<=|<|>=|>|==|=|\\+|-";
String line = "a <= b < c ";
Matcher matcher = Pattern.compile(regex).matcher(line);
while (matcher.find()) {
System.out.println(matcher.start() + " : " + matcher.group());
}
Output:
2 : <=
7 : <
The trick is that, before the regex matches <
, of <=
, it will already be matched by <=
, as it comes before <
.