AomSet
AomSet

Reputation: 383

Split string, and get a certain word

I have a file containing the following info, as an example:

User: James Latitude: 1.0 Longitude: 2.0 Date: Mon Sep 16 22:15:48 CEST 2013

User: Romio Latitude: 11.0 Longitude: 2.0 Date: Mon Sep 16 22:15:48 CEST 2013

User: "Sander" Latitude: -1.0 Longitude: 28.0 Date: Mon Sep 16 22:15:48 CEST 2013

I want to get the names: James, Romio and Sander, and nothing else for now. How can I do this? I tried using the split and indexOf methods, but I am using it wrong. Here is some of my remaining code, after deleting it many times:

public boolean uniqueUserName(String userName) {
    String[] currentName = null;
    String nameToValidate = null;

    int i = 0;

    try {
        while(reader.readLine() != null) {
            currentName = reader.readLine().split(":");             
            nameToValidate = currentName[i++];  

            if(nameToValidate.equals(userName)) {
                return false;
            }

            System.out.println("Names: " + nameToValidate);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }       
    return true;
}

I know that I don't get the names when using the split, and I end up getting a NullPointer. Perhaps I need to introduce some extra signs/expressions in the file, so that it is easier to split? I'm all ears to suggestions.

Thanks

Upvotes: 0

Views: 101

Answers (1)

Mena
Mena

Reputation: 48444

You could use regular expressions to find any word character between "User: " and "Latitude", accepting optional whitespace and double quotes, as such:

// input Strings
String james = "User: James Latitude: 1.0 Longitude: 2.0 Date: Mon Sep 16 22:15:48 CEST 2013";
String romio = "User: Romio Latitude: 11.0 Longitude: 2.0 Date: Mon Sep 16 22:15:48 CEST 2013";
String sander = "User: \"Sander\" Latitude: -1.0 Longitude: 28.0 Date: Mon Sep 16 22:15:48 CEST 2013";

// Pattern:                                group 
//                                          for
//                                         name
Pattern p = Pattern.compile("User:\\s+?\"?(\\w+?)\"?\\s+?Latitude");
// Matching...
Matcher m = p.matcher(james);
if (m.find()) {
// If found, referencing group 1 and printing it
    System.out.println(m.group(1));
}
// Etc...
m = p.matcher(romio);
if (m.find()) {
    System.out.println(m.group(1));
}
m = p.matcher(sander);
if (m.find()) {
    System.out.println(m.group(1));
}

Output:

James
Romio
Sander

Upvotes: 1

Related Questions