How to find words within a range in a TreeSet <String> using regular expressions (java)

I iterate over the TreeSet and print it out:

while (it.hasNext()) {
  System.out.println(it.next());
}

      

output:

after
explorers
giant
hoping
internet
into
.
.
.
virtual 
world

      

However, I would like to only print out those lines whose first character is in the mz range. I am playing with java.util.regex, no success:

String pattern = "[^m-z]";

      

Do I have the right idea? Or is there an easier way to do this? All I want to do is make sure I only print the lines in the TreeSet that are the first character in the mz range.

+1


source to share


5 answers


First of all, your regex is wrong. Do you want to

"^[m-z]"

      



Second, you are not showing the code you are using to execute.

Third: if you want to do anything besides regex and iteration, you should look into SortedSet.tailSet. This is probably what your teacher wants.

+5


source


I don't know about regular expressions, but you can easily find those Elements that start with a letter from mz:

wordSet.tailSet("m", true);

      

Usually you should use subSet () with a lower bound and the next character from the upper bound, but since z is the last character, it is not easy to do.



To get the set from 'b' to 'y' you would do

wordSet.subSet("b", true, "z", false);

      

+4


source


I agree this sounds fishy like homework, but here we go ...

while (it.hasNext()) {
    String element = it.next();
    if (element.toLowerCase().matches("^[m-z].*")) {
        System.out.println(element);
    }
}

      

+3


source


seems like homework, but anyway, "[^ mz]" means NOT mz

try putting "^" outside "[]"

Have a look at Pattern class and BTW, tryString.matches()

+2


source


I know the original poster was discussed using regex, but it may have had a problem to solve, decided to use regex and now has two issues to solve .

while (it.hasNext()) {
    String element = (String) it.next();
    char c = element.charAt(0);
    if (c >= 'm' && c <= 'z') {
        System.out.println(element);
    }
}

      

This is similar to his requirement in bold in the original question, although it is possible that his teacher dictated the use of regular expressions.

EDIT: I only bothered to read the full question just now. However, I still find it important to understand that regular expressions are not the only way to solve this problem.

+2


source







All Articles