如何在java中拆分字符串并包含分隔符

时间:2017-03-22 18:01:15

标签: java string split delimiter

我想分割这个字符串" AHHHAAAAARTFUHLAAAAAHV"使用分隔符" AAAA"并将其保存到包含分隔符的数组中。 (期望输出:[AHHHA,AAAA,RTFUHLA,AAAA,HV])。我有下面的代码,但输出与我想要的输出不一样。

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用(?=AAAA[^A]|(?<=AAAA(?=[^A])))

(?=AAAA[^A]:预测匹配AAAA和非A字符

|:或

(?<=AAAA(?=[^A]))):积极回顾以匹配AAAA与先行,以确保没有A个字符

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

输出:

[AHHHA, AAAA, RTFUHLA, AAAA, HV]