如何使用java代码判断第一个字符是否为数字呢?
下文笔者讲述使用java代码检测第一个字符是否为数字的方法分享,如下所示
实现思路:
使用正则表达式检测字符串的开头是否为数字
s.matches("\\d.*")
// 或
s.matches("[0-9].*")
例:
public static void main(String[] args) {
String s1 = "asd";
String s2 = "1asd";
String s3 = "$asd";
String s4 = "89898";
String s5 = "abc78";
// 数字验证的正则表达式
String regex = "\\d.*";
System.out.println(Pattern.compile(regex).matcher(s1.subSequence(0, 1)).find());
System.out.println(Pattern.compile(regex).matcher(s2.subSequence(0, 1)).find());
System.out.println(Pattern.compile(regex).matcher(s3.subSequence(0, 1)).find());
System.out.println(Pattern.compile(regex).matcher(s4.subSequence(0, 1)).find());
System.out.println(Pattern.compile(regex).matcher(s5.subSequence(0, 1)).find());
System.out.println("============");
}
------运行以上代码,将输出以下信息-------
false
true
false
true
false
============
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


