2

I am trying to split the below multiline string by scanner. I want to split the lines starting with "A|"

Input
A|14|23|656
B|15|ga|a
A|11|424|6262

Output

Group
    A|14|23|656
    B|15|ga|a

Group
    A|11|424|6262

I have tried scanner as below.

public static void main(String[] args) {
        String abcd = "A|14|23|656\r\nB|15|ga|a\r\nA|11|424|6262";

        try (final Scanner scan = new Scanner(abcd)) {
            scan.useDelimiter("^A\\|");
            while (scan.hasNext()) {
                System.out.println("Group");
                System.out.println("A|" + scan.next());
            }
        }
    }

Actual: It is just considering the matching A| on the first line not on other lines.

Group
A|14|23|656
B|15|ga|a
A|11|424|6262
Patan
  • 17,073
  • 36
  • 124
  • 198
  • see [this answer](https://stackoverflow.com/a/45293555/2310289) for information on how to use multi-line split – Scary Wombat Jul 25 '17 at 05:21
  • @ScaryWombat. Thanks. I tried that solution String[] paragraphs = abcd.split("(?m)^A\\|$\\R?"); But this does not seem to work. – Patan Jul 25 '17 at 05:28
  • @Patan I think even the first line also is not getting considered. Could you please try this : `String abcd = "B|15|ga|a\r\nA|14|23|656\r\nA|11|424|6262"` and check the output please. – Ashraf.Shk786 Jul 25 '17 at 05:51
  • @Ashraf.Shk786. Thanks for noticing. Yes it prints the first line too. How can I avoid that – Patan Jul 25 '17 at 05:55
  • @Patan `scan.useDelimiter("(?m)^A\\|");` should work but if not working I'll suggest you try to do this: `Step1.` split/separate the string with new line and store them as array `Step2.` then after try to print the data inside array and do pattern matching for `A|` , and also keep printing the data until the pattern get matched once it matches print new line or do whatever stuffs you are required and repeat `step2` again and again till last element is printed from the array. – Ashraf.Shk786 Jul 25 '17 at 06:20

2 Answers2

0

By default, regex in java only match at the beginning and the end of the entire input sequence.

So, you have to enable multiline mode to consider each line separately. Just preceed your regex by flag (?m) to enable multi-line mode.

scan.useDelimiter("(?m)^A\\|");

See Demo here: https://ideone.com/1HwXCU

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
0

Please try this:

try (final Scanner scan = new Scanner(abcd)) {
        scan.useDelimiter("(?:(^A\\|)|(\nA\\|))");
        while (scan.hasNext()) {
            System.out.println("Group");
            System.out.println("A|" + scan.next());
        }
    }
Harneet Singh
  • 2,328
  • 3
  • 16
  • 23