Elad Benda
Elad Benda

Reputation: 36654

java grouping regex fail to match string+text

I wrote this test

@Test
public void removeRequestTextFromRouteError() throws Exception {
    String input = "Failed to handle request regression_4828 HISTORIC_TIME from=s:33901510 tn:27825741 bd:false st:Winifred~Dr to=s:-1 d:false f:-1.0 x:-73.92752 y:40.696857 r:-1.0 cd:-1.0 fn:-1 tn:-1 bd:true 1 null false null on subject RoutingRequest";
    final String answer = stringUtils.removeRequestTextFromError(input);
    String expected = "Failed to handle request _ on subject RoutingRequest";
    assertThat(answer, equalTo(expected));
}

which runs this method, but fails

public String removeRequestTextFromError(String answer) {
    answer = answer.replaceAll("regression_\\d\\[.*?\\] on subject", "_ on subject");
    return answer;

}

The input text stays the same and not replaced with "_"

how can I change the pattern matching to fix this?

Upvotes: 0

Views: 50

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

As an alternative to the answer given by @TheLostMind, you can try breaking your input into 3 pieces, the second piece being what you want to match and then remove.

Each quantity in parentheses, if matched, will be available as a capture group. Here is the regex with the capture groups labelled:

(.*)(regression_\\d+.* on subject)(.*)
 $1             $2                 $3

You want to retain $1 and $3:

public String removeRequestTextFromError(String answer) {
    answer = answer.replaceAll("(.*)(regression_\\d+.* on subject)(.*)", "$1$3");
}

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

You are using the a wrong regex. You are escaping [ and ] (not necessary at all) and using \\d instead of \\d+. Also, you should use a positive look-ahead instead of actually selecting and replacing the String "on subject"

Use :

public static void main(String[] args) {
    String input = "Failed to handle request regression_4828 HISTORIC_TIME from=s:33901510 tn:27825741 bd:false st:Winifred~Dr to=s:-1 d:false f:-1.0 x:-73.92752 y:40.696857 r:-1.0 cd:-1.0 fn:-1 tn:-1 bd:true 1 null false null on subject RoutingRequest";
    final String answer = input.replaceAll("regression_.* (?=on subject)", "_ ");
    System.out.println(answer);
    String expected = "Failed to handle request _ on subject RoutingRequest";
    System.out.println(answer.equals(expected));
}

O/P :

Failed to handle request _ on subject RoutingRequest
true

Upvotes: 1

Related Questions