Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting A String In Java?

This is in Java 7

I do not know regular expressions, so I was wondering if anybody knew how I could use the split method to get all usernames out of the string:

{tchristofferson=10, mchristofferson=50}

and then add the usernames to a String[] array? These are just two usernames in there, but I want this to work for an endless amount of usernames.

Usernames require the following format:

3-16 characters, no spaces, A-Z upper and lower case and 0-9, only special character is _ (underscore).

like image 405
tchristofferson Avatar asked May 24 '26 15:05

tchristofferson


1 Answers

This looks like JSON, so the "right" answer would probably be to use a JSON parser. If this is not an option, you can remove the enclosing {}, split the string according to ", ", and then split each string according to the = sign, taking the first item:

String input = "{tchristofferson=10, mchristofferson=50}";
List<String> users =
    Arrays.stream(input.substring(1, input.length() - 1).split(", "))
          .map(s -> s.split("=")[0])
          .collect(Collectors.toList());
like image 62
Mureinik Avatar answered May 26 '26 04:05

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!