2

我正在尝试通过一组运算符来查看其中一个运算符是否位于字符串中。

例如:

String[] OPERATORS    = { "<", "<=", ... };
String line = "a <= b < c ";

我将如何通过一个循环来检查运算符是否在字符串中?

另外,假设我的方法发现“<”位于“ < =”的字符串中

但是,我正在寻找实际的字符串“ <= ”。我将如何进行会计处理?

4

4 回答 4

6

我会使用正则表达式而不是所有运算符的数组。此外,请确保运算符在您的正则表达式中的确切顺序,即<=应该在之前<,同样,==应该在之前=

String regex = "<=|<|>=|>|==|=|\\+|-";

String line = "a <= b < c ";

Matcher matcher = Pattern.compile(regex).matcher(line);

while (matcher.find()) {
    System.out.println(matcher.start() + " : " + matcher.group());
} 

输出

2 : <=
7 : <

诀窍是,在正则表达式匹配<, of之前<=,它已经被 匹配了<=,就像它之前一样<

于 2014-03-26T17:16:05.340 回答
3

像这样的东西应该解释 >= 匹配 >。

String[] OPERATORS = {"<=>", "<=", ">=", ">", "=" ..} //The key here is that if op1 contains op2, then it should have a lower index than it

String copy = new String(line);

for(String op : OPERATORS)
{
    if(copy.contains(op))
    {
        copy = copy.replaceAll(op, "X"); //so that we don't match the same later
        System.out.println("found " + op);
    }
}

如果您还需要索引,那么当您需要用多个相同长度的 X 替换 OP 时。如果您可以拥有每个操作的倍数并且您需要所有操作的位置,那么它仍然需要更多的工作。但是这个问题并没有过于具体。无论如何,这应该让你滚动。

于 2014-03-26T17:14:53.913 回答
0

这是我要做的:

for(String operator : OPERATORS)
{
    if(Pattern.compile("[\\s\\w]" + operator + "[\\s\\w]").matcher(line).find())
    {
        System.out.println(operator + " found in " + line);
    }
}

它应该可以正常工作,不会<<=.

完整代码:

import java.util.regex.Pattern;

public class Test
{
    public static void main(String[] args)
    {
        String[] OPERATORS = { "<", "<="};
        String line = "a <= b < c ";

        for(String operator : OPERATORS)
        {
            if(Pattern.compile("[\\s\\w]" + operator + "[\\s\\w]").matcher(line).find())
            {
                System.out.println(operator + " found in " + line);
            }
        }
    }
}
于 2014-03-26T17:00:48.297 回答
0

这只有在操作员两边都有空间时才有效:

for (String operator : OPERATORS) {
    Matcher m = Pattern.compile("\\s\\" + operator + "\\s").matcher(line);
    while (m.find())
         System.out.println((m.start() + 1) + " : " + m.group());
}

这可以在没有任何特殊操作符的情况下工作。

于 2014-03-26T17:27:55.293 回答