[英]Java String pattern with words and numbers
I have some problems with the pattern in Java.我对 Java 中的模式有一些问题。 I followed all of the steps in Regex but these lines of code are not working!
我遵循了 Regex 中的所有步骤,但这些代码行不起作用!
Pattern p = Pattern.compile("[a-zA-Z]{4}-[0-9]{1}");
if (p.matcher(id).matches())
this.id = id;
else
System.out.println("Wrong format!");
Whenever I type ABCD-0123, it is false and prints out wrong format每当我输入 ABCD-0123 时,它都是错误的并打印出错误的格式
[0-9]{1}
means only one digit (in the end of you pattern), and you are invoking matches
, which considers the whole input. [0-9]{1}
表示只有一位数字(在你模式的末尾),并且你正在调用matches
,它考虑了整个输入。
Either adjust the digits to {4}
or whatever you need, or invoke find
instead of matches
.要么将数字调整为
{4}
或您需要的任何内容,要么调用find
而不是matches
。
The latter ( find
) will... find the pattern inside your given input, instead of matching against the whole input.后者(
find
)将...在给定的输入中找到模式,而不是匹配整个输入。
Useful for patterns describing part of the input.对于描述部分输入的模式很有用。
Replace the regex condition by [a-zA-Z]{4}-[0-9]+将正则表达式条件替换为 [a-zA-Z]{4}-[0-9]+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.