2

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]

4
  • 2
    try Arrays.toString(y.split("(?=AAAA[^A]|(?<=AAAA(?=[^A])))")) ? Commented Mar 22, 2017 at 18:16
  • 1
    Your desired splitting rule is ambiguous. AHHHAAAAA could be split into either AHHH, AAAA, A or AHHHA, AAAA. What is your expected outcome for AAAAAAAAA (9 As)? AAAAA, AAAA, or A, AAAA, AAAA, or ...? Commented Mar 22, 2017 at 18:16
  • @Pavneet_Singh WOW! thank you that did the job! Thank you that helped a lot. Commented Mar 22, 2017 at 18:25
  • @Socowi I thought so. Im practically toying around the split function so i was confused. Btw thank you so much for the idea Commented Mar 22, 2017 at 18:25

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe (?=AAAA(?!A)|(?<=AAAA(?!A))) is also good to use here.
@WiktorStribiżew i have tested negative look ahead against mine but seems like they are taking little more time though they are surely concise
Actually, I believe they will work differently as well. Anyway, it is just in case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.