简体   繁体   English

在 java 中使用算术运算符和函数拆分字符串

[英]Splitting the String with arithmetic operators and functions in java

I need some guidance on how to split a string with arithmetic operators and functions in java for the example String is:我需要一些关于如何使用 java 中的算术运算符和函数拆分字符串的指导,例如 String 是:

"string1"+"String2" >= 10 * function1() / function2()

operators may be:运营商可能是:

+ - * / ** / % / ( ) = != > < <= >=

After Split I need the output like:拆分后,我需要 output ,例如:

array[0]=string1
array[1]=string2
array[2]=10

I need only things inside the double quotes and contants or numbers, not a functions(function1()) or operators.我只需要双引号和内容或数字内的东西,而不是函数(function1())或运算符。

I need regular expression for this problem我需要正则表达式来解决这个问题

You can remove all operators from string and then match everything except strings with () in the end.您可以从字符串中删除所有运算符,然后将除字符串之外的所有内容都与最后的()匹配。

I recommend to create a parser, eg using JavaCC or maybe parboiled https://github.com/sirthias/parboiled/wiki/ (haven't tried that one yet)我建议创建一个解析器,例如使用 JavaCC 或parboiled https://github.com/sirthias/parboiled/wiki/ (还没有尝试过)

If you need a regex for extracting things inside the double quotes and numbers, then you can use this java code:如果您需要一个正则表达式来提取双引号和数字中的内容,那么您可以使用此 java 代码:

public static void main(String[] args) {
    Pattern p = Pattern.compile("\"(\\w+)\"|\\b\\d+\\b");
    Matcher m = p.matcher(
        "\"string1\"+\"String2\" >= 10 * function1() / function2()");
    List<String> parts = new ArrayList<String>();
    while (m.find()) {
        if (m.group(1) != null)
            parts.add(m.group(1));
        else
            parts.add(m.group(0));
    }
    System.out.println(Arrays.toString(parts.toArray(new String[] {})));        
}

which outputs:输出:

[string1, String2, 10]

Note: I'm not sure that regex is the best tool in this case.注意:我不确定正则表达式是这种情况下的最佳工具。 As others suggested you may want to investigate the use of a parser.正如其他人建议的那样,您可能想要调查解析器的使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM