0

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?

enter image description here

bbKing
  • 179
  • 1
  • 8
  • 1
    Your issue may be fixed by putting a maximum on the number of digits that can occur between commas. For example: `"(?<=\\G\\d{1,10},\\d{1,10},\\d{1,10}),"` – MikeM May 06 '22 at 22:28
  • 3
    I am using Java 17 and compiler doesn't generate any problems with this code. IntelliJ complained about it BUT still despite this problem ***allowed me to run*** your code. It looks like your IDE is trying to prevent you from doing something not wise (using bug in regex which can be fixed an any moment), even if it is *legal*. – Pshemo May 06 '22 at 22:37
  • I am now using `\\d{1,3}` as recommended by @MikeM. Thanks to all for cross checking. – bbKing May 06 '22 at 22:41

1 Answers1

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.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • I didn't find the right place to turn the setting off, but as you stated it compiles and produces the correct result. Thank you very much. – bbKing May 06 '22 at 22:36