Java 使用正则表达式检查字符串是否以数字字符开头和结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18019584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if a string starts and ends with number characters using regex
提问by Matt Smith
I'm trying
我想
String string = "123456";
if(string.startsWith("[0-9]") && string.endsWith("[0-9]")){
//code
}
And the if clause is never called.
并且从不调用 if 子句。
采纳答案by arshajii
Don't use a regex:
不要使用正则表达式:
Character.isDigit(string.charAt(0)) &&
Character.isDigit(string.charAt(string.length()-1))
(see Character.isDigit())
回答by arjacsoh
The methods startsWith()and endsWith()in class Stringaccept only String, not a regex.
方法startsWith()和endsWith()类String只接受字符串,而不是正则表达式。
回答by sashok724
You can use:
您可以使用:
String string = "123test123";
if(string.matches("\d.*\d"))
{
// ...
}
回答by Boris the Spider
You can use the matchesmethod on Stringthusly:
您可以在以下情况下使用该matches方法String:
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
回答by Md. Mostafizur Rahman
Please follow the code snippet.
请按照代码片段进行操作。
String variableString = "012testString";
Character.isDigit(string.charAt(0)) && variableString.Any(c => char.IsUpper(c));

