0

How to write the regular expression for below kind of String such that I get response in below format ?

"abc, -xyz, lmn, qwe,-yui"

Basically I need to parse above string in List<String> as

abc, -xyz
lmn
qwe, -yui

Below code is working fine when there is exactly one space before hyphen(-) ex:

"abc, -xyz"

but not working when there is no or more than one space, ex:

"abc,  -xyz"

Regular expression I tried:

List<String> items = Arrays.stream(order.split("(?!, -),")).map(String::trim).map(String::toLowerCase).collect(Collectors.toList());

Please provide the code which parse with any number of spaces and also explain the logic for the same.

aarish_codev
  • 43
  • 1
  • 5

1 Answers1

0

Instead of splitting your string you can actually find all results using "(.+?)". This finds all string between ". Here is the full example:

String input = "\"abc, -xyz\", \"lmn\", \"qwe,-yui\"";
Pattern pattern = Pattern.compile("\"(?<item>.+?)\"");
Matcher matcher = pattern.matcher(input);
List<String> items = new ArrayList<>();
while (matcher.find()) {
    items.add(matcher.group("item"));
}
items.forEach(System.out::println);

The result will be this:

abc, -xyz
lmn
qwe,-yui

You also can use .trim(),toLowercase() before adding an item to the list if you need that.

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56