Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java regex repetition not allowed inside lookbehind

I am looking for a way to split a string after every 3rd comma. I have found an old answer from 2013 Split a String at every 3rd comma in Java which I think is outdated. If I copy paste the accepted answer as is I get a compile error saying

repetition not allowed inside lookbehind

I am using Intellij with Java 11, if that matters

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Below the example from accepted answer from the linked post

String data = "0,0,1,2,4,5,3,4,6";
String[] array = data.split("(?<=\\G\\d+,\\d+,\\d+),"); 
for(String s : array){
    System.out.println(s);
}

What is the proper way if the above is not correct anymore?

enter image description here

>Solution :

There are various cases where unbounded repetition in lookahead/behind is not allowed. However, this isn’t one of them.

You’ve found an IntelliJ bug. That bug is being reported by intellij (not javac). It is incorrectly thinking this is one of those cases where you can’t do that.

Tell intellij to stop whinging. It’s somewhat likely that you can’t do that. File a bug report, I guess. Point is, if you take that source file and just run javac ThatFile.java it compiles and runs without issues.

You can work around it by ‘faking out’ intellij. It’s doing a compile time check on that string because intellij realizes that, being a constant, it can do that. You can probably dodge intellij’s broken analysis here by making it a dynamic string. For example:

data.split((System.currentTimeMillis() < 0 ? "A?" : "") + "(?<=.. rest of regex here ..");

IntelliJ is now likely to determine that the string is dynamic and therefore cannot be analysed. Thus, it won’t.

But, before jumping through such silly hoops, there may be a setting in intellij somewhere about ‘smart analysis of regex literals’ or whatnot. Turn it off, at least, until this bug is fixed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading