开发者

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:

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

operators may be:

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

After Spl开发者_开发知识库it I need the output like:

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.

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, e.g. using JavaCC or maybe parboiled https://github.com/sirthias/parboiled/wiki/ (haven't tried that one yet)


If you need a regex for extracting things inside the double quotes and numbers, then you can use this java code:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜