将字符串转换为标记

时间:2017-03-25 13:59:34

标签: java regex string

我正在尝试根据正则表达式将字符串拆分为标记。但是split()给出错误 Illegal Escape Sequencce

我正在尝试将以下字符串拆分为令牌。

例如,以下字符串转换为

1 2.0 3.145 4.0

+ - /

&安培;此

String[] tokens = expression.split("\\+\\-\\x\\/");

这是我写过的正则表达式,但这有一些问题并且会出错。

    public KeyValuePair<string, string> CheckForNonNullArguments()
    {

        System.Reflection.PropertyInfo[] properties = typeof(BaseBLL).GetProperties();
        foreach (System.Reflection.PropertyInfo property in properties)
            if (property.GetValue(this, null) != null && (!property.GetValue(this, null).Equals("NULL") && !property.GetValue(this, null).ToString().Equals("0")) && !String.IsNullOrEmpty(property.GetValue(this, null).ToString()))
                return new KeyValuePair<string, string>(property.Name.ToString(), property.GetValue(this, null).ToString());
        return new KeyValuePair<string, string>("", "");
        //if (property.GetValue(this, null) != null) GetName(() => property); ;
    }

我做错了什么?

修改: 我的最终目标是评估一个包含数学表达式的字符串。计算其结果。是否有可以在Android上使用的库?

2 个答案:

答案 0 :(得分:0)

将您的正则表达式更新为expression.split("[-+/]")

如果你想要阵列,你可以使用它:

 List<String> operators = new ArrayList<>();
 List<String> operands = new ArrayList<>();
 StringTokenizer st = new StringTokenizer(expression, "+-/", true);
 while (st.hasMoreTokens()) {
    String token = st.nextToken();

    if ("+-/".contains(token)) {
       operators.add(token);
    } else {
       operands.add(token);
    }
 }

答案 1 :(得分:0)

评估一个表达式是非常棘手的,比如应该在哪个顺序计算它们之前已经解决了这个问题:http://www.geeksforgeeks.org/expression-evaluation/

并且

@Roma Khomyshyn链接也很有用。

相关问题