Compare how you would accomplish the two tasks mentioned below with and without regular expressions. The problem:
The format for an SMS-based food delivery will be:
PABUSOG slash or comma repeated an infinite number of times @
// The quantity can only be numeric. For simplicity, assume that quantity is always an integer
e.g. PABUSOG STRFRY_SMAI/2 HSHBRWN_BRGR/1 COFEEFLT/1 @En311
it will capture the following:
STRFRY_SMAI – 2
HSHBRWN_BRGR – 1
COFEEFLT – 1
this is my sample code: // doing with regex
String message = "PABUSOG ASD_ASD/1 ASD_ASA/2";
Pattern pattern = Pattern.compile("PABUSOG(\\s+([A-Z]+_[A-Z]+)(/|,)([0-9]))+"
,Pattern.CASE_INSENSITIVE);
Matcher m = pattern.matcher(message);
try
{
if (m.matches())
{
String food = m.group(2);
String quantity = m.group(4);
System.out.println(food + " -- " + quantity + "\\n");
}
}
catch (NullPointerException e)
{
}
it displays the ASD_ASA — 2, it overrides the 1st one which is ASD_ASD/1.
it must display
ASD_ASD — 1
ASD_ASA — 2
You cannot accomplish that with a single regex giving you all the data inside groups. And there’s no great need for complex regex either. But still if you prefer regex try searching for pattern iteratively.
Without complex regex you can do the following by using
StringAPI:To skip items started with
@you can either addinside loop or limit
subListin the following way if you sure that such item is always present and terminates the sequence:Arrays.asList(items).subList(1, items.length - 1).By the way, your pattern
[A-Z]+_[A-Z]+won’t matchCOFEEFLTfrom your example.