Using regular expressions (not recommended)
There is no direct way of expressing this. It is in fact almost identical to figuring out if a given number is within a specific range. (That is, providing a regular expression matching digits within the range 123-456.)
You can "encode" it with a fairly complex regular expression though. A process which I've described here:
For the specific example of "abc"
to "def"
you would write it like this:
a
followed
b
followed by c-z
, or
c-z
followed by any character, or
b-c
followed by any two characters, or
d
followed by
a-d
followed by any character, or
e
followed by
Here it is in code:
String pattern = "a(b[c-z]|[c-z][a-z])|[bc][a-z][a-z]|d([a-d][a-z]|e[a-f])";
for (String s: "abc acc ace amf def efg khp mlo".split(" "))
System.out.println(s + (s.matches(pattern) ? " matches" : ""));
Output:
abc matches
acc matches
ace matches
amf matches
def matches
efg
khp
mlo
Using String.compareTo
(recommended)
You should consider comparing the strings instead:
"abc".compareTo(s) <= 0 && s.compareTo("def") <= 0
Example:
String lower = "abc", upper = "def";
for (String s: "abc acc ace amf def efg khp mlo".split(" ")) {
boolean match = lower.compareTo(s) <= 0 && s.compareTo(upper) <= 0;
System.out.println(s + (match ? " matches" : ""));
}
Output:
abc matches
acc matches
ace matches
amf matches
def matches
efg
khp
mlo