我正在尝试,if (nuevo_precio.getText().matches("/^\\d+$/"))
但到目前为止效果不佳...
6 回答
在 Java 正则表达式中,您不使用分隔符/
:
nuevo_precio.getText().matches("^\\d+$")
由于String.matches()
(or Matcher.matcher()
) 强制整个字符串与返回的模式匹配true
,^
and$
实际上是多余的,可以在不影响结果的情况下删除。与 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+)?$
分解它:
^ 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+")
应该这样做。
仅供参考,该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