Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex, replace certain characters except

Tags:

java

regex

swing

I have this string "u2x4m5x7" and I want replace all the characters but a number followed by an x with "". The output should be: "2x5x" Just the number followed by the x. But I am getting this: "2x45x7"

I'm doing this:

String string = "u2x4m5x7";

String s = string.replaceAll("[^0-9+x]","");

Please help!!!

like image 524
The Storyteller Avatar asked Mar 04 '23 02:03

The Storyteller


2 Answers

Here is a one-liner using String#replaceAll with two replacements:

System.out.println(string.replaceAll("\\d+(?!x)", "").replaceAll("[^x\\d]", ""));

Here is another working solution. We can iterate the input string using a formal pattern matcher with the pattern \d+x. This is the whitelist approach, of trying to match the variable combinations we want to keep.

String input = "u2x4m5x7";
Pattern pattern = Pattern.compile("\\d+x");
Matcher m = pattern.matcher(input);
StringBuilder b = new StringBuilder();

while(m.find()) {
    b.append(m.group(0));
}

System.out.println(b)

This prints:

2x5x
like image 114
Tim Biegeleisen Avatar answered Mar 05 '23 15:03

Tim Biegeleisen


It looks like this would be much simpler by searching to get the match rather than replacing all non matches, but here is a possible solution, though it may be missing a few cases:

\d(?!x)|[^0-9x]|(?<!\d)x

https://regex101.com/r/v6udph/1

Basically it will:

  • \d(?!x) -- remove any digit not followed by an x
  • [^0-9x] -- remove all non-x/digit characters
  • (?<!\d)x -- remove all x's not preceded by a digit

But then again, grabbing from \dx would be much simpler

like image 42
David542 Avatar answered Mar 05 '23 14:03

David542