'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
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rzwitserloot |

