Regular expression for words containing letters in alphabetical order JAVA

My student (high school) asked me a question about a regular expression corresponding to a word containing letters in alphabetical order. Honestly, I do not know how to create a regular expression. An example of matching words, the size of the letters does not matter:

abc, aWZ, gOR, bor 
+6
source share
3 answers
 ^a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*$ 

must work

+16
source

This should work:

 (?i)a*b*c*...z* 

It would be easy to build in a loop.

 StringBuilder b = new StringBuilder(64); b.append("(?i)"); for (int i = 'a'; i <= 'z'; i++) b.append((char)i).append('*'); return Pattern.compile(b.toString()).matcher(input).matches(); 
+8
source

This is not a good problem for regex, it is almost certainly easier to check it in a for loop:

 import static java.lang.Character.isLetter; import static java.lang.Character.toLowerCase; public boolean alphabeticalOrder(String word) { for (int i = 0; i < word.length() - 1; i++) { if (!isLetter(word.charAt(i)) || toLowerCase(word.charAt(i + 1)) < toLowerCase(word.charAt(i))) return false; } return isLetter(word.charAt(word.length() - 1)); } 

Alternatively, the following regular expression will also match correctly (only for ASCII alphabetic characters) when passed to CASE_INSENSITIVE :

 ^a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*$ 
+2
source

All Articles