5 Replies Latest reply: Jul 9, 2009 7:49 AM by 807588 RSS

    Problem with String split

    807588
      String patternString = "Once|Twice|Thrice|Four";
      String[] patternArr = patternString.split("\\|");

      I need out put like {Once,*Twice|Thrice*,Four}
      not like {Once,Twice,Thrice,Four}

      Can anybody help on this
        • 1. Re: Problem with String split
          807588
          ragavarnan_call_screen wrote:
          String patternString = "Once|Twice|Thrice|Four";
          String[] patternArr = patternString.split("\\|");

          I need out put like {Once,*Twice|Thrice*,Four}
          not like {Once,Twice,Thrice,Four}
          So you only want to split on the first pipe char and the last pipe char. Is that right? What do you want from

          "a|b|c|d|e|f|g|h"
          • 2. Re: Problem with String split
            807588
            Yes I want to split first and last pipe character only.I want to escape the second pipe character from the split
            • 3. Re: Problem with String split
              807588
              Hi ragavarnan_call_screen,

              There's no need to use the split method. You may use indexOf, lastIndexOf and substring methods to do the job.
                      String test = "Once|Twice|Thrice|Four";
                      String[] res = new String[3];
                      res[0] = test.substring(0, test.indexOf("|"));
                      res[1] = test.substring(test.indexOf("|") + 1, test.lastIndexOf("|"));
                      res[2] = test.substring(test.lastIndexOf("|") + 1);
              • 4. Re: Problem with String split
                807588
                I want to know if i can escape the pipe symbol in the split method.

                For example my StringObj = "I want to know*|*from You|else meet me";

                for this case i want to escape the first pipe symbol.
                This i can do with other possible options, but that is not feasible to me,
                • 5. Re: Problem with String split
                  807588
                  ragavarnan_call_screen wrote:
                  I want to know if i can escape the pipe symbol in the split method.

                  For example my StringObj = "I want to know*|*from You|else meet me";

                  for this case i want to escape the first pipe symbol.
                  This i can do with other possible options, but that is not feasible to me,
                  Why not ? You can use
                    System.out.println(Arrays.toString(s.split("(?<=^[^|]{1,1000})\\||\\|(?=[^|]+$)")));
                  but the non-regex solution is much easier to understand.