开发者

string matching problem?

开发者 https://www.devze.com 2023-02-18 23:12 出处:网络
i want to parse a textfile. if \":\" occurs then i want to split the 开发者_如何学Goarray in two pieces. the second piece gets investigated further: if it contains \"in \" (note the space, this is imp

i want to parse a textfile. if ":" occurs then i want to split the 开发者_如何学Goarray 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);
    }
  }
}


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
}


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消