2017-02-27 261 views
0

我想在Java中编写一个正则表达式,它将帮助我识别具有特定格式的字母数字的匹配项:9个字符长,前面5个数字为[0-9],接下来的三个大写字符[A-Z]和最后一个字符是数字[0-9]。我现在想要的是:Java正则表达式字母数字匹配

Matcher m = Pattern.compile("^[0-9]{1,5}[A-Z]{3}[0-9]{1}?$", 
    Pattern.UNICODE_CASE).matcher(str.toString()); 

while (m.find()) { 
    System.out.println("Match found::" + m.group(0)); 
} 

当我只通过字母数字,例如, 24135AB6,上面的代码工作并找到匹配项。然而,如果我通过一个更大的表达式,例如John goes 24135AB6 away back24135AB6 24135AB6,我的代码不起作用。我怎样才能解决这个问题?

回答

0

首先,您的代码在传递A234B时也会起作用,因为[0-9]{1,5}意味着1到5次出现。

尝试使用此正则表达式:如您所愿字母字符,而不是两个

^[0-9]{5}[A-Z]{3}[0-9]?$ 

当然24135AB6不会作为输入工作。另外,如果你想在模式之前忽略任何乱码,你需要删除^,如果你想忽略模式后的任何东西,你需要删除$符号。

^开头的意思是:我的字符串必须以未来

$末的意思如下正好开始:我的字符串必须与我在这里定义的最终

+0

谢谢。我会试试看。 –

0
The regex (?<=^|\\s) ensures that either start of the input or a white space before the sequence. 
The regex (?<=^|\\s)[0-9]{1,5}[A-Z]{3}[0-9]{1}\\b\\w* will find sequences that starts with a 5 numbers 3 Uppercase letters and 1 number followed by 0 or more words. 


String input="24135ABE6 John goes 24135ABA6 away back 24135ABC6 24135ABD6A"; 
Pattern regex = Pattern.compile("(?<=^|\\s)[0-9]{1,5}[A-Z]{3}[0-9]{1}\\b\\w*"); 

Matcher matcher = regex.matcher(input); 
while (matcher.find()) 
{ 
     System.out.println(matcher.group()); 
} 

output: 

24135ABE6 
24135ABA6 
24135ABC6