1

I'm writing a Java console program which looks up the vendor for a given mac address.

Using 'arp -a' through runtime i receive a string such as:

"172.17.7.144            44-94-fc-68-b7-03       dynamic"

I'm having difficulty splitting the string to just retrieve the mac address, the spacing between the IP address and the mac changes depending on length, so splitting via spaces doesn't appear to work.

What is the best way to retrieve the data from a string like this?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Matt Harris
  • 33
  • 1
  • 3

1 Answers1

3

Like @Andrea mention in comment you can easily use :

String str = "172.17.7.144            44-94-fc-68-b7-03       dynamic";
String[] spl = str.split("\\s+");

Outputs

172.17.7.144 
44-94-fc-68-b7-03
dynamic

Another solution if you want to get only the Mac address you can use Patterns (take a look about the pattern What is a regular expression for a MAC Address?) like this :

Pattern pat = Pattern.compile("([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})");
Matcher mat = pat.matcher(str);
while (mat.find()) {
    System.out.println(mat.group());
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    Why the overhead of `replaceAll()`? Why not just do `.split("\\s+")`? Sorry, but that's just a really bad example, guiding people the wrong way, so down-vote from me. – Andreas Jun 03 '17 at 12:53
  • 1
    but i don't know why this down-vote, it is a correct solution why you down-vote it @Andreas ?? not all people are good like you so please a useful comment is better – Youcef LAIDANI Jun 03 '17 at 12:56
  • 1
    Down-vote is in effect because answer is giving a very bad example, leading people astray. Guiding people down the wrong track is *not useful*. – Andreas Jun 03 '17 at 12:58
  • ok i already fix it why you still insist and don't remove this down-vote then @Andreas ? – Youcef LAIDANI Jun 03 '17 at 12:59
  • 1
    It can take years for people to unlearn bad advice. I'm leaving down-vote until bad advice is *removed* from answer. – Andreas Jun 03 '17 at 13:01