dnup1092
dnup1092

Reputation: 375

How to get string between - and ^ or after - at the end

I have following string from which I want extract string which is there between - and ^. And I also want the string which is after - only if its the last - in the given string.

090186-1052^0901164-1052^090180046165-585^0980046166-24064^090186a980046170-24064^00046168-36495^0901846169-46731^0d019616e-34985^8004616f-13010^186a9846167-778

I have written the following code but I'm getting all the values except 778 which is comming null instead.

public static void main(String args[]){
        Pattern pattern = Pattern.compile("-(.+?)\\^|-(.+)");
        String str = "090186-1052^0901164-1052^090180046165-585^0980046166-24064^090186a980046170-24064^00046168-36495^0901846169-46731^0d019616e-34985^8004616f-13010^186a9846167-778";
        Matcher matcher = pattern.matcher(str);
          while (matcher.find()) {
                System.out.println(matcher.group(1));
            }
    }

Upvotes: 2

Views: 59

Answers (4)

assylias
assylias

Reputation: 328618

An alternative is to split the string twice:

String[] splitOnDash = str.split("-");
for (int i = 1; i < splitOnDash.length; i++) {
  System.out.println(splitOnDash[i].split("\\^")[0]);
}

Output:

1052
1052
585
24064
24064
36495
46731
34985
13010
778

Or if you fancy streams:

Pattern.compile("-").splitAsStream(str)
        .skip(1)
        .map(s -> s.split("\\^")[0])
        .forEach(System.out::println);

Upvotes: 0

RealSkeptic
RealSkeptic

Reputation: 34628

The appropriate regex would be

Pattern pattern = Pattern.compile("-(.+?)(?:\\^|$)");

This reads: - followed by any characters (grouped, reluctant), followed by (non-captured) either ^ or end-of-input.

This way the matched number is always in the first group.

Upvotes: 5

Mariano
Mariano

Reputation: 6511

You're using 2 groups:

-(.+?)\\^|-(.+)
 ^^^^^     ^^^^
   1        2

Your last match is in

matcher.group(2)

Upvotes: 2

npinti
npinti

Reputation: 52185

As shown here, the number you are after is available in the second group.

Changing your code to the below should fix the issue:

    Pattern pattern = Pattern.compile("-(.+?)\\^|-(.+)");
    String str = "090186-1052^0901164-1052^090180046165-585^0980046166-24064^090186a980046170-24064^00046168-36495^0901846169-46731^0d019616e-34985^8004616f-13010^186a9846167-778";
    Matcher matcher = pattern.matcher(str);
      while (matcher.find()) {
            if(matcher.group(1) != null)
                System.out.println(matcher.group(1));
            else if(matcher.group(2) != null)
                System.out.println(matcher.group(2));
        }

Yields:

1052
1052
585
24064
24064
36495
46731
34985
13010
778

Upvotes: 3

Related Questions