Nic
Nic

Reputation: 3

Splitting strings with multiple lines in android

I have the following string:

"ISL-1027

20:13:02:22:00:76"

i.e. bluetooth name and MAC address

I need MAC address on a separate string. What is the best way to use split() in this case?

Thanks

Upvotes: 0

Views: 2045

Answers (3)

Rene M.
Rene M.

Reputation: 2690

Depending on that how your string is formated is not sure, but the format of a mac-address is defined. I would not try to split the string and hope that index n is the correct value. Instead I would use regulare expression to find the correct position of a string that matches the mac-address format.

Here is a litle example (not tested):

String input = "ISL-1027

20:13:02:22:00:76"

Pattern macAddrPattern = Pattern.compile("[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\:[0-9a-fA-F]{2}\");

String macAdr = parseMacAddr(input);

public String parseMacAddr(String value) {
  Matcher m = macAddrPattern.matcher(value);

  if (m.matches()) {
    return value.substring(m.start(),m.end());
  }

  return null;
}

This should always work.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

split("\n") you can use this."\n" will be the separator here.

   String str = "ISL-1027" +
            "\n" +
            "20:13:02:22:00:76";
    String[] arr= str.split("\n");
    System.out.println("Bluetooth  Name: "+arr[0]);
    System.out.println("MAC address: "+arr[1]);

Out put:

Bluetooth  Name: ISL-1027
MAC address: 20:13:02:22:00:76

If your input String like this ISL-1027 20:13:02:22:00:76(separate by a space) use follows

    String str = "ISL-1027 20:13:02:22:00:76";      

    String[] arr= str.split(" ");
    System.out.println("Bluetooth  Name: "+arr[0]);
    System.out.println("MAC address: "+arr[1]);

Upvotes: 3

joescii
joescii

Reputation: 6533

Split matching on any white space and include the DOTALL mode switch:

split("(?s)\\s+");

The DOTALL will make the regex work despite the presence of newlines.

Upvotes: 0

Related Questions