Regex replacing everything before a predefined range of chars - Java

Viewed 38

I have string values where I want to remove or replace everything that comes before "TV|TH". My problem is that despite using the correct syntax, the string seems to stay the same.

 String test = "10TH";
 String replaceBeforeSide =  test.replaceAll("^\\(TH|TV)+", "");
 System.out.println(replaceBeforeSide);

//Desired result = "TH";

1 Answers

Converting my comment to answer so that solution is easy to find for future visitors.

You could use a simple regex with a capture group:

replaceBeforeSide = test.replaceAll(".+?(TH|TV)", "$1");

or even shorter:

replaceBeforeSide = test.replaceAll(".+?(T[HV])", "$1");

Using .+?, we are matching 1+ of any character (non-greedy) before matching (TH|TV) that we capture in group #1.

In replacement we just put $1 back so that only string before (TH|TV) is removed.

We could also use a lookahead and avoid capture group:

replaceBeforeSide = test.replaceAll(".+?(?=T[HV])", "");

If you want to match ignore case then use inline modifier (?i):

replaceBeforeSide = test.replaceAll("(?i).+?(?=T[HV])", "");
Related