Home > Enterprise >  Split the String on second time if exist and otherwise split on the first time
Split the String on second time if exist and otherwise split on the first time

Time:03-30

Hi i have a string "I am Anna. I am from California". I want to cut the string at second "am", if second "am" exist.otherwise i want to split at first "am". I am now using split method and tried pattern matching. Please help

   String mydata = "I am Anna. I am from California";
    Pattern pattern = Pattern.compile("I(.*?) A");
    Matcher matcher = pattern.matcher(mydata);
    if (matcher.find())
    {
        System.out.println(matcher.group(1));
    }

CodePudding user response:

Split after am where there are no occurrences of am in the remaining input:

String[] parts = mydata.split("(?<=\\bam\\b)(?!.*\\bam\\b)");

If you just want the first part:

String intro = mydata.split("(?<=\\bam\\b)(?!.*\\bam\\b)")[0];
  • Related