I am trying to see if a given host name appears in a list of hosts in the form of comma separated string like the following:
String list = "aa.com,bb.com,cc.com,dd.net,ee.com,ff.net";
String host1 = "aa.com"; // should be a match
String host2 = "a.com"; // shouldn't be a match
String host3 = "ff.net" // should be a match
// here is a test for host1
if (list.matches(".*[,^]" + host1 + "[$,].*")) {
System.out.println(host1 + " matched");
}
else {
System.out.println(host1 + " not matched");
}
But I got not matched for host (aa.com) but then I am not very familiar with regex. Please correct me!
BTW I don't want to use a solution where you split the host list into an array and then doing matching there. It was too slow because the host list can be quite long. Regex apporoach can be even worse but I was trying to make it work first.
matches()matches the whole string, not a part of it. You would have to either split the string and compare to each element, or usePattern ...; Matcher ...;.if(Arrays.asList(list.split(",")).contains(host1)){//matched}? Or you could split the string first, and put all the elements in anHashSet. Then checking if it's valid or not will be done in constant time.