T A
T A

Reputation: 1756

Java regex match anything except a single expression

I am trying to replace everything except a specific expression including digits in java using only the replaceAll() method and a single regex.

Given the String P=32 N=5 M=2 I want to extract each variable independently. I can match the expression N=5 with the regex N=\d, but I can't seem to find an inverse expression that will match anything but N=\d, where x may be any digit.

I do not want to use Pattern or Matcher but solve this using regex only. So for x, y, z being any digit, I want to be able to replace everything but the expression N=y in a String P=x N=y M=z:

String input = "P=32 N=5 M=2";
output = input.replaceAll(regex, "");
System.out.println(output);
// expected "N=5"

Upvotes: 0

Views: 83

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626709

You may use

s = s.replaceAll("\\s*\\b(?!N=\\d)\\w+=\\d+", "").trim(); 

See the Java demo and the regex demo.

Details

  • \s* - 0+ whitespaces
  • \b - a word boundary
  • (?!N=\d) - immediately to the right, there should be no N= and any digit
  • \w+ - 1+ letters/digits/_
  • = - an = sign
  • \d+ - 1+ digits.

Upvotes: 1

Related Questions