Checking if a string starts and ends with number characters using regex

廉价感情. 提交于 2021-02-08 13:24:27

问题


I'm trying

String string = "123456";    
if(string.startsWith("[0-9]") && string.endsWith("[0-9]")){
                        //code
                    }

And the if clause is never called.


回答1:


Don't use a regex:

Character.isDigit(string.charAt(0)) && 
                              Character.isDigit(string.charAt(string.length()-1))

(see Character.isDigit())




回答2:


The methods startsWith() and endsWith() in class String accept only String, not a regex.




回答3:


You can use:

String string = "123test123";
if(string.matches("\\d.*\\d"))
{
    // ...
}



回答4:


You can use the matches method on String thusly:

public static void main(String[] args) throws Exception {
    System.out.println("123456".matches("^\\d.*?\\d$"));
    System.out.println("123456A".matches("^\\d.*?\\d$"));
    System.out.println("A123456".matches("^\\d.*?\\d$"));
    System.out.println("A123456A".matches("^\\d.*?\\d$"));
}

Output:

true
false
false
false



回答5:


Please follow the code snippet.

String variableString = "012testString";
Character.isDigit(string.charAt(0)) && variableString.Any(c => char.IsUpper(c));


来源:https://stackoverflow.com/questions/18019584/checking-if-a-string-starts-and-ends-with-number-characters-using-regex

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