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.
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);
source to share
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.
source to share