Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple java regex with backreference does not work

Tags:

java

regex

I have trouble to replace a string with a backreference of a regular expression: Nothing is replaced and i always end up with my input.
My code:

String input="A12.3 bla bla my input";
input = StringUtils.replacePattern(
            input, "^([A-Z]\\d{2}\\.\\d)",
            "$1");
System.out.println(input);

The main problem is that I can not change the java code but only the input, regex and group reference.

Do you have any suggestions about any other regex pattern that matches my needs or what is going wrong?


StringUtils is of Apache Commons Lang

like image 846
Allipon Avatar asked Apr 27 '26 13:04

Allipon


1 Answers

You are replacing same matched pattern by itself. Probably you meant:

String input="A12.3 bla bla my input";
input = StringUtils.replacePattern(
            input, "^([A-Z]\\d{2}\\.\\d).*$", "$1");
//                                      ^^^
System.out.println(input);

.*$ will match the input till end.

like image 66
anubhava Avatar answered Apr 30 '26 03:04

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!