1

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?

asked Nov 17, 2014 at 10:13

1 Answer 1

3

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.
answered Nov 17, 2014 at 10:16
Sign up to request clarification or add additional context in comments.

4 Comments

Shouldn't . be escaped as well?
yep, escaping the $ will do the job.
@MarounMaroun: DOT has no special meaning in replacement but $ does have.
Escaping the $ did the job! Thanks!!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.