I am trying to go through an array of Operators to see if one of the operators is located in the String.
For example:
String[] OPERATORS = { "<", "<=", ... };
String line = "a <= b < c ";
How would I go about going through a loop that checks to see if an operator is in the string?
Also, say my method found that "<" is located in the string at "<= "
However, I am looking for the actual string " <= ". How would I go about accounting for that?
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 <
.