If all you need is a number section and a label section, you can simplify the regex as follows:
ABCD E (\d+(?:,\d+)*)(?: (\w+))?
Legenda
ABCD E
(
\d+
(?:,\d+)*
)
(?:
(\w+)
)?
By adding some flexibility (replacing spaces with a tabbed group too [ \t]), the above becomes the following:
ABCD[ \t]+E[ \t]+(\d+(?:,\d+)*)(?:[ \t]+(\w+))?
Regex Demo
Link
Demo code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String ln = System.lineSeparator();
String input = "ABCD E 1234 L1" + ln
+ "ABCD E 1234,2345 L2" + ln
+ "ABCD E 4567" + ln
+ "ABCD E 2435,4679" + ln
+ "ABCD E 2435,4679,657 L6";
final Pattern labelPattern = Pattern.compile("ABCD[ \\t]+E[ \\t]+(\\d+(?:,\\d+)*)(?:[ \\t]+(\\w+))?");
Matcher m = labelPattern.matcher(input);
int line = 1;
while(m.find()) {
System.out.print("Line " + line++ + ": ");
if ( ! m.group(2) )
System.out.println("'" + m.group(1) + "'");
else
System.out.println("'" + m.group(1) + "', '" + m.group(2)+ "'");
}
Exit
Line 1: '1234', 'L1'
Line 2: '1234,2345', 'L2'
Line 3: '4567'
Line 4: '2435,4679'
Line 5: '2435,4679,657', 'L6'
source
share