7
Input-> Input!RC + Calc!R[1]C[1]

In Output I want to operate on these :

RC and R[1]C[1]

My attempt :

private static void findMatch(String formula) {
         Matcher m = Pattern.compile("\\W(R(\\[(.+?)\\])?C(\\[(.+?)\\]))")
         .matcher(formula);
        // Matcher m = Pattern.compile(
        // "\\W(R(\\[(.+?)\\])?C) | \\W(R(\\[(.+?)\\])?C(\\[(.+?)\\]))")
        //  .matcher(formula);
        for (; m.find(); m.reset(formula)) {
            System.out.println(m.group(3));
        }

    }

It does not look for the second pattern as well it goes into infinite loops.

Whats wrong with this ?

2 Answers 2

7

Try the following:

String formula = "Input!RC + Calc!R[1]C[1]";
Matcher m = Pattern.compile("\\W(R(\\[(.+?)\\])?C(\\[(.+?)\\])?)").matcher(formula);
while (m.find()) {
    System.out.println(m.group(1));
}

Output:

RC
R[1]C[1]

The main change here is how the loop works, what I have above is the typical way for iterating over matches of a pattern. I am also printing m.group(1) instead of m.group(3) because it is the first group that will contain the entire match except for the !, which I think is what you want.

The only change to your regex here was adding the ? after the second (\\[(.+?)\\]) group to make it optional.

Sign up to request clarification or add additional context in comments.

2 Comments

I have only one concern with this : when I am trying to replace a particular group, say R[1]C, it also replaces part for R[1]C[1] which I do not want and gives erroraneous output. what do u think, how can I handle such situation ?
You need to write your regex such that it only matches the strings you want to replace. If you want to replace R[1]C and not R[1]C[1] then you should change the (\\[(.+?)\\])? after the C to (?!\\[(.+?)\\]). This is a negative lookahead which means "fail the match if the next characters in the string match \\[(.+?)\\]".
3

If you look at this piece of code:

for (; m.find(); m.reset(formula)) {
    System.out.println(m.group(3));
}

For every loop, it calls successively m.reset(formula), resetting the matcher so that it starts at 0, then m.find(), which look for the next match in the string. Since you called reset() before, the next match is the first match. Therefore you have an infinite loop.

If you want to find all matches in the string, simply write:

while(m.find()) {
    System.out.println(m.group(1));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.