简体   繁体   中英

Regular Expressions - match a string containing “+” and “-”

I have a string, say 1+++-3--+++++2 that includes + and - sign. What I want to do is to represent the + and - part with + or - sign. If there are an odd number of - sign in the string, I will replace it with - , and + if that is an even number. How can I do that using regex?

For example, I have a math expression, say 1+-+-2-+--+3 . It will be replaced by 1+2-3

You can create an array of the operators and use a for loop to count all occurrences of one character. For example:

String expression = "1+++-3--+++++2";
String[] str = expression.split("[0-9]+");

for(op : str) {
    int count = 0;
    for(int i =0; i < str.length(); i++)
        if(op.charAt(i) == '-')
            count++;

    if(count % 2 == 0) {
        op = "-";
    }
    else {
        op = "+";
    }
}

After assigning the modified one-character operators in str[] , it should be relatively simple to write the new expression.

based on the assumption that the format will be from that calculator example.

//assumed format for input: <any number><any number of `-` and/or `+`><any number>

// 1++---+22+--1 will be 1-22+1
String input = "1++---+22+--1";
for (String s : input.split("[^-+]+");) {
    s = s.trim();
    if (!"".equals(s)) {
        String newStr = s.matches("[+]*-([+]*-[+]*-)*[+]*") ? "-" : "+";
        input = input.replace(s, newStr);
    }
}
System.out.println(input);

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