Steven Verheyen
Steven Verheyen

Reputation: 169

Java - Regex String replacement

I want to replace some parts of a String with Regex. It's the 192001Z part of the string I want to replace.

Code:

String met = "192001Z 17006KT 150V210 CAVOK 11/07 Q1004 NOSIG";
String regexZ = "[0-9].{5}Z";
met = met.replaceAll(regexZ, "${.now?string(\"ddHHmm\")}Z");

I get an error when I want to replace a part of the String with ${.now?string(\"ddHHmm\")}Z.

But when I e.g. replace ${.now?string(\"ddHHmm\")}Z with ThisNeedsToBeReplaced everything works just fine. So my guess is that something is wrong with the string I want to use to replace parts of my original string (met).

The error I receive is Illegal group reference.

Does anyone have an idea what's wrong with ${.now?string(\"ddHHmm\")}Z?

Upvotes: 1

Views: 67

Answers (1)

anubhava
anubhava

Reputation: 784988

You need to use:

met = met.replaceAll("\\b\\d{6}Z\\b", "\\${.now?string(\"ddHHmm\")}Z");
  • Correct regex to match 192001Z is \b\d{6}Z\b
  • You need to escape $ in replacement as well otherwise it is considered a back reference e.g. $1, $2 etx.

Upvotes: 3

Related Questions