111

In Java is there a way to find out if first character of a string is a number?

One way is

string.startsWith("1")

and do the above all the way till 9, but that seems very inefficient.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Omnipresent
  • 29,434
  • 47
  • 142
  • 186

6 Answers6

264
Character.isDigit(string.charAt(0))

Note that this will allow any Unicode digit, not just 0-9. You might prefer:

char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');

Or the slower regex solutions:

s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")

However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.

To make the entire condition one line and avoid length checks, you can alter the regexes to the following:

s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")

If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
  • Re: "you must first be sure that the string isn't empty" - true and more then that - you must also make sure its not null as if it is all the displayed methods will throw exceptions. You can either directly check ( e.g. `((null!=s) && Character.isDigit(s.charAt(0)) )` ) or use tricks like `Character.isDigit((s?s:"X").charAt(0)) ` – epeleg Jun 17 '13 at 06:39
8

Regular expressions are very strong but expensive tool. It is valid to use them for checking if the first character is a digit but it is not so elegant :) I prefer this way:

public boolean isLeadingDigit(final String value){
    final char c = value.charAt(0);
    return (c >= '0' && c <= '9');
}
Kiril Aleksandrov
  • 2,601
  • 20
  • 27
  • 12
    1) `function` is not Java. 2) This only allows Arabic numerals, not Chinese, Indian, etc. That might be what you prefer, but it isn't specified in the question. 3) I already covered this exact solution in my answer four years ago. – Michael Myers May 23 '13 at 15:44
1

IN KOTLIN :

Suppose that you have a String like this :

private val phoneNumber="9121111111"

At first you should get the first one :

val firstChar=phoneNumber.slice(0..0)

At second you can check the first char that return a Boolean :

firstChar.isInt() // or isFloat()
milad salimi
  • 1,580
  • 2
  • 12
  • 31
0
regular expression starts with number->'^[0-9]' 
Pattern pattern = Pattern.compile('^[0-9]');
 Matcher matcher = pattern.matcher(String);

if(matcher.find()){

System.out.println("true");
}
Narayan Yerrabachu
  • 1,714
  • 1
  • 19
  • 31
  • 2
    You don't need the `{1,1}` suffix, which means that "the preceding pattern must appear between 1 and 1 times". This means exactly the same as the pattern does on its own. – Andrzej Doyle Jun 04 '13 at 14:43
  • This solution does not work since String.matches and Pattern API tries to match complete string and not just first character – Amrish Pandey Apr 21 '15 at 09:23
0

I just came across this question and thought on contributing with a solution that does not use regex.

In my case I use a helper method:

public boolean notNumber(String input){
    boolean notNumber = false;
    try {
        // must not start with a number
        @SuppressWarnings("unused")
        double checker = Double.valueOf(input.substring(0,1));
    }
    catch (Exception e) {
        notNumber = true;           
    }
    return notNumber;
}

Probably an overkill, but I try to avoid regex whenever I can.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
-1

To verify only first letter is number or character -- For number Character.isDigit(str.charAt(0)) --return true

For character Character.isLetter(str.charAt(0)) --return true

Apu
  • 1