[英]What's the Java regular expression for an only integer numbers string?
我正在尝试if (nuevo_precio.getText().matches("/^\\\\d+$/"))
但到目前为止得不到好结果......
在Java正则表达式中,您不使用分隔符/
:
nuevo_precio.getText().matches("^\\d+$")
由于String.matches()
(或Matcher.matcher()
)强制整个字符串与模式匹配以返回true
,因此^
和$
实际上是多余的,可以在不影响结果的情况下删除。 与JavaScript,PHP(PCRE)或Perl相比,这有点不同,其中“匹配”意味着在目标字符串中查找与模式匹配的子字符串。
nuevo_precio.getText().matches("\\d+") // Equivalent solution
但是,将它留在那里并没有什么坏处,因为它表示意图并使正则表达式更具可移植性。
要限制正好是 4位数:
"\\d{4}"
正如其他人已经说过的那样,java不使用分隔符。 你想要匹配的字符串不需要尾部斜杠,所以代替/^\\\\d+$/
你的字符串应该是^\\\\d+$
。
现在我知道这是一个古老的问题,但这里的大多数人都忘记了非常重要的事情。 正确的整数正则表达式:
^-?\d+$
打破它:
^ String start metacharacter (Not required if using matches() - read below)
-? Matches the minus character (Optional)
\d+ Matches 1 or more digit characters
$ String end metacharacter (Not required if using matches() - read below)
当然,在Java中你需要一个双反斜杠而不是常规的反斜杠,所以匹配上述正则表达式的Java字符串是^-?\\\\d+$
注意:如果您使用.matches()
,则不需要^$
(字符串开头/结尾)字符:
欢迎使用Java的错误名称
.matches()
方法...它尝试并匹配所有输入。 不幸的是,其他语言也纷纷效仿:(- 取自这个答案
正则表达式仍然适用于^$
。 即使它是可选的,我仍然将它包含在正则表达式可读性中,就像在其他情况下默认情况下你不匹配整个字符串一样(大多数情况下,如果你不使用.matches()
) d使用这些字符
相反的情况:
^\D+$
\\D
是不是数字的一切。 \\D
(非数字)否定\\d
(数字)。
请注意,这仅适用于整数 。 双打的正则表达式:
^-?\d+(\.\d+)?$
打破它:
^ String start metacharacter (Not required if using matches())
-? Matches the minus character. The ? sign makes the minus character optional.
\d+ Matches 1 or more digit characters
( Start capturing group
\.\d+ A literal dot followed by one or more digits
)? End capturing group. The ? sign makes the whole group optional.
$ String end metacharacter (Not required if using matches())
当然用Java代替\\d
和\\.
你有双反斜杠,如上例所示。
Java不使用斜杠来分隔正则表达式。
.matches("\\d+")
应该这样做。
FYI String.matches()
方法必须匹配整个输入才能返回true
。
即使在像perl这样的语言中,斜杠也不是正则表达式的一部分; 它们是分隔符 - 如果是应用程序代码,则与正则表达式无关
你也可以去否定来检查数字是否是纯数字。
Pattern pattern = Pattern.compile(".*[^0-9].*");
for(String input: inputs){
System.out.println( "Is " + input + " a number : "
+ !pattern.matcher(input).matches());
}
public static void main(String[] args) {
//regex is made to allow all the characters like a,b,...z,A,B,.....Z and
//also numbers from 0-9.
String regex = "[a-zA-z0-9]*";
String stringName="paul123";
//pattern compiled
Pattern pattern = Pattern.compile(regex);
String s = stringName.trim();
Matcher matcher = pattern.matcher(s);
System.out.println(matcher.matches());
}
正则表达式适用于数字,而不是整数:
Integer.MAX_VALUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.