简体   繁体   中英

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 Split 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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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