-1

I have a reply message in a String and I want to split it to extract a value.

My String reply message format is:

REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE,...);

My requirement is to get the value ABC024049364194 from the above string format.

I tried using this code, but it hasn't worked:

String[] arrOfStr = str.split(",", 5); 

for (String a : arrOfStr) 
    System.out.println(a);
MTCoster
  • 5,868
  • 3
  • 28
  • 49
Maxtech
  • 111
  • 16
  • 1
    If you split the `String` by comma, you have to fetch the correct index afterwards. As far as I can see, it will be on index 2, so do `String[] arr = str.split(","); System.out.println(arr[2]);` – deHaar Feb 11 '19 at 15:32
  • 2
    Define "it hasn't worked". Please see the [How to Ask](https://stackoverflow.com/help/how-to-ask) page. That said, if you have a *general* need to do this, regex isn't always the best solution. – Dave Newton Feb 11 '19 at 15:32
  • 1
    Hi, what means `it hasn't worked` ? Please describe the behavior or the error which you are getting, from the first look you are on the right way, and if you want only ABC.. value, then you need token as on the second index `[2]`, indexing is from zero, so first `[0]` is `REPLY(MSGID`, `[1] 15`, `[2] ABC024049364194` – xxxvodnikxxx Feb 11 '19 at 15:36

2 Answers2

2

If you split the String, you will simply need to access the token at index 2.

// <TYPE>(<ARGUMENTS>)
String message = "REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE);";
Matcher m = Pattern.compile("(\\w+)\\((.+)\\)").matcher(message);
if (m.find()) {
    String type = m.group(1);
    String[] arguments = m.group(2).split(",");
    System.out.println(type + " = " + arguments[2]); // REPLY = ABC024049364194
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
1
public static void main(String[] args) {
        String str = "REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE,...)";
        String code = str.split(",")[2];
        System.out.println(code);

    }

Will work if your code is always after 2 coma

Limmy
  • 697
  • 1
  • 13
  • 24