john
john

Reputation: 1

string matching problem?

i want to parse a textfile. if ":" occurs then i want to split the array in two pieces. the second piece gets investigated further: if it contains "in " (note the space, this is important) or "out " the arraylist ports gets populated. if neither "in " nor "out " is in the second half of the original string, generics gets populated. i tried it with the following code:

if (str.matches("\\:")) {
  String[] splitarray = str.split("\\:");
  if (splitarray[1].matches("in ")) {
    ports.add(str);
  } else {  
    if (splitarray[1].matches("out ")) {
      ports.add(str);
    } else {
      generics.add(str);
    }
  }
}

Upvotes: 0

Views: 1055

Answers (2)

JB Nizet
JB Nizet

Reputation: 691735

matches determines if the whole String matches the expression, not if some part of the string matches the expression. For such a simple case, I wouldn't go with regexp. Just use indexOf to find your substring:

int indexOfColon = str.indexOf(':');
if (indexOfColon >= 0) {
    String afterColon = str.substring(indexOfColon + 1);
    int indexOfIn = afterColon.indexOf("in ");
    // you get the idea
}

Upvotes: 1

hanumant
hanumant

Reputation: 1101

See if this helps

public static void main(String[] args) {
    // assuming only 1 occurence of ':'
    String a = "sasdads:asdadin ";
    ArrayList<String> ports = new ArrayList<String>();
    ArrayList<String> generics = new ArrayList<String>();
    if (a.contains(":")) {
        String[] strings = a.split(":");
        if (strings[1].contains("in ")) {
            ports.add(strings[1]);
        }else{
            generics.add(strings[1]);
        }
    }
    System.out.println();
}

Upvotes: 0

Related Questions