Search code examples
javastringsplitdelimiter

How to split a string in java and include the delimiter


I want to split this string "AHHHAAAAARTFUHLAAAAAHV" using a delimiter "AAAA" and save it to an array including the delimiter. (desired output: [AHHHA, AAAA, RTFUHLA, AAAA ,HV]). I have the following codes below but the output is not the same to my desired output.

  String y = "AHHHAAAAARTFUHLAAAAAHV";
  System.out.println(Arrays.toString(y.split("((?<=AAAA)|(?=AAAA))")));

OUPUT: [AHHH, A, AAA, A, RTFUHL, A, AAA, A, HV]


Solution

  • You can use (?=AAAA[^A]|(?<=AAAA(?=[^A])))

    (?=AAAA[^A] : look-ahead to match AAAA and a non A char

    | : or

    (?<=AAAA(?=[^A]))) : positive-look-behind to match AAAA with lookahead to make sure there is no A character

    String y = "AHHHAAAAARTFUHLAAAAAHV";
    System.out.println(Arrays.toString(y.split("(?=AAAA[^A]|(?<=AAAA(?=[^A])))")));
    

    Output :

    [AHHHA, AAAA, RTFUHLA, AAAA, HV]