The Dark Knight
The Dark Knight

Reputation: 383

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

Upvotes: 0

Views: 85

Answers (2)

jcera
jcera

Reputation: 345

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);

Upvotes: 1

deezy
deezy

Reputation: 1480

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.

Upvotes: 2

Related Questions