mahmood
mahmood

Reputation: 24735

Searching a HashSet with regex

There is a HashSet of strings and I want to search for key. The HashSet content looks like

AB
A1-A2-A3
A1
A2-A3
AD-A1
AZ
...

If I use theSet.contains("A1"), then it will return A1 only. However, I want to get A1-A2-A3 and A1 and AD-A1. The special character in my data file is - which is the delimiter in case a line contains that.

If I don't use HashSet and search within an array of strings, then I know how to use matcher(). Any solution for the HashSet?

Upvotes: 1

Views: 449

Answers (2)

sniperd
sniperd

Reputation: 5274

Well, you could try something like...

Take all the keys, and construct a very long ugly string

,AB,A1-A2-A3,A1,A2-A3,AD-A1,AZ,...

Then do a find all 'kind' of regex for A1:

uglystring = ",AB,A1-A2-A3,A1,A2-A3,AD-A1,"
thelist = re.findall("([^,]*A1[^,]*)", uglystring)
print (thelist)

That is in python. Pretty ugly, but maybe get you going in the right direction?

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198211

There is no better solution than to iterate through the entire HashSet and run the matcher over each element.

for (String str : set) {
  if (str.contains("A1")) {
    // do whatever with str
  }
}

Upvotes: 6

Related Questions