Determine if string starts with letters A through I

烈酒焚心 提交于 2019-12-01 03:35:48

You don't need regular expressions for this.

Try this, assuming you want uppercase only:

char c = string.charAt(0);
if (c >= 'A' && c <= 'I') { ... }

If you do want a regex solution however, you can use this (ideone):

if (string.matches("^[A-I].*$")) { ... }
if ( string.charAt(0) >= 'A' && string.charAt(0) <= 'I' )
{
}

should do it

How about this for brevity?

if (0 <= "ABCDEFGHI".indexOf(string.charAt(0))) {
    // string starts with a character between 'A' and 'I' inclusive
}
Jin

Try

string.charAt(0) >= 'a' && string.charAt(0) <= 'j'
char c=string.toLowerCase().charAt(0);
if( c >= 'a' && c <= 'i' )
    ...

This makes it easy to extract it as a method:

public static boolean startsBetween(String s, char lowest, char highest) {
    char c=s.charAt(0);
    c=Character.toLowerCase(c);  //thx refp
    return c >= lowest && c <= highest;
}

which is HIGHLY preferred to any inline solution. For the win, tag it as final so java inlines it for you and gives you better performance than a coded-inline solution as well.

if ( string.toUpperCase().charAt(0) >= 'A' && string.toUpperCase().charAt(0) <= 'I' )

should be the easiest version...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!