-8

I have got a string

$key1={331015EA261D38A7}
$key2={9145A98BA37617DE}
$key3={EF745F23AA67243D}

How do i split each of the keys based on "$" and the "next line" element? and then place it in an Arraylist?

The output should look like this: Arraylist[0]:

$key1={331015EA261D38A7}

Arraylist[1]:

$key2={9145A98BA37617DE}

Arraylist[2]:

$key3={EF745F23AA67243D}
mhasan
  • 3,703
  • 1
  • 18
  • 37
Shawn
  • 27
  • 4

3 Answers3

3

If you just want to split by new line, it is as simple as :

yourstring.split("\n"):
aleroot
  • 71,077
  • 30
  • 176
  • 213
0

yourstring.split(System.getProperty("line.separator"));

Simon Ludwig
  • 1,754
  • 1
  • 20
  • 27
  • 1
    This will work only if text uses same line separator in defined in system, which is not guaranteed. – Pshemo Oct 08 '16 at 10:51
  • Yes, right. but also its system independent – Simon Ludwig Oct 08 '16 at 10:55
  • @SimonLudwig I think you misunderstand. If you are parsing a file, it has the linebreaks it has. The system is irrelevant. Using the system line separator is not the right choice; avoiding the line separator entirely is. – Boris the Spider Oct 08 '16 at 10:58
  • "but also its system independent" quite opposite. Value of `System.getProperty("line.separator")` depends **only** on system. For instance if I create file on Linux where lines are separated with `\n` and will try to split it on Windows which is using `\r\n` then your solution can't work since `\r\n` will not match `\n`. If you are looking for independent solution than you can try with `\r?\n|\r` (since `split` is using regex). – Pshemo Oct 08 '16 at 10:58
0

Don't split, search your String for key value pairs:

\$(?<key>[^=]++)=\{(?<value>[^}]++)\}

For example:

final Pattern pattern = Pattern.compile("\\$(?<key>[^=]++)=\\{(?<value>[^}]++)\\}");
final String input = "$key1={331015EA261D38A7}\n$key2={9145A98BA37617DE}\n$key3={EF745F23AA67243D}";
final Matcher matcher = pattern.matcher(input);
final Map<String, String> parse = new HashMap<>();
while (matcher.find()) {
    parse.put(matcher.group("key"), matcher.group("value"));
}
//print values
parse.forEach((k, v) -> System.out.printf("Key '%s' has value '%s'%n", k, v));

Output:

Key 'key1' has value '331015EA261D38A7'
Key 'key2' has value '9145A98BA37617DE'
Key 'key3' has value 'EF745F23AA67243D'

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166