问题
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