[英]How to check a string starts with numeric number?
我有一個包含字母數字字符的字符串。
我需要檢查字符串是否以數字開頭。
謝謝,
參見isDigit(char ch)
方法:
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html
並使用String.charAt()
方法將其傳遞給 String 的第一個字符。
Character.isDigit(myString.charAt(0));
抱歉,我沒有看到您的 Java 標簽,只是在閱讀問題。 反正我會在這里留下我的其他答案,因為我已經把它們打出來了。
爪哇
String myString = "9Hello World!";
if ( Character.isDigit(myString.charAt(0)) )
{
System.out.println("String begins with a digit");
}
C++ :
string myString = "2Hello World!";
if (isdigit( myString[0]) )
{
printf("String begins with a digit");
}
正則表達式:
\b[0-9]
我認為你應該使用正則表達式:
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
String neg = "-123abc";
String pos = "123abc";
String non = "abc123";
/* I'm not sure if this regex is too verbose, but it should be
* clear. It checks that the string starts with either a series
* of one or more digits... OR a negative sign followed by 1 or
* more digits. Anything can follow the digits. Update as you need
* for things that should not follow the digits or for floating
* point numbers.
*/
Pattern pattern = Pattern.compile("^(\\d+.*|-\\d+.*)");
Matcher matcher = pattern.matcher(neg);
if(matcher.matches()) {
System.out.println("matches negative number");
}
matcher = pattern.matcher(pos);
if (matcher.matches()) {
System.out.println("positive matches");
}
matcher = pattern.matcher(non);
if (!matcher.matches()) {
System.out.println("letters don't match :-)!!!");
}
}
}
您可能想要調整它以接受浮點數,但這將適用於負數。 其他答案對否定無效,因為它們只檢查第一個字符! 更具體地了解您的需求,我可以幫助您調整這種方法。
這應該有效:
String s = "123foo";
Character.isDigit(s.charAt(0));
System.out.println(Character.isDigit(mystring.charAt(0));
編輯:我搜索了 java 文檔,查看了字符串類上的方法,它可以讓我獲得第一個字符並查看 Character 類上的方法,看看它是否有任何方法來檢查這樣的事情。
我想,你可以在問它之前做同樣的事情。
EDI2:我的意思是,嘗試做一些事情,閱讀/查找,如果你找不到任何東西——問。
第一次發帖的時候弄錯了。 isDigit 是 Character 類的靜態方法。
使用像^\\d
這樣的正則表達式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.