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
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
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]); 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.
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.