0

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?

2
  • Did you try printing the result you get from your remove.. method? Commented Sep 4, 2016 at 7:42
  • Use return answer.replaceAll("regression_\\d.* on subject", "_ on subject"); inside the removeRequestTextFromError method. Commented Sep 4, 2016 at 7:50

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

i want to add regression_\\d+
@EladBenda - Yes, you could do that
1

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

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.