使用正则表达式提取ISBN

Ada*_*orm 4 java regex

我有一个非常长的字符串,我想解析一个在子字符串"ISBN"之后出现的数值.但是,这种13位数的分组可以通过" - "字符进行不同的排列.示例:(这些都是有效的ISBN)123-456-789-123-4,OR 1-2-3-4-5-67891234,OR 12-34-56-78-91-23-4.基本上,我想在潜在的ISBN上使用正则表达式模式匹配器来查看是否存在有效的13位ISBN.我如何"忽略"" - "字符,以便我可以正则表达式\d{13}?我的功能:

public String parseISBN (String sourceCode) {
  int location = sourceCode.indexOf("ISBN") + 5;
  String ISBN = sourceCode.substring(location); //substring after "ISBN" occurs
  int i = 0;
  while ( ISBN.charAt(i) != ' ' )
    i++;
  ISBN = ISBN.substring(0, i); //should contain potential ISBN value
  Pattern pattern = Pattern.compile("\\d{13}"); //this clearly will find 13 consecutive numbers, but I need it to ignore the "-" character
  Matcher matcher = pattern.matcher(ISBN); 
  if (matcher.find()) return ISBN;
  else return null;
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 8

演示第二种选择:

String ISBN = "ISBN: 123-456-789-112-3, ISBN: 1234567891123";

Pattern pattern = Pattern.compile("(\\d-?){13}");
Matcher matcher = pattern.matcher(ISBN);

while (matcher.find())
    System.out.println(matcher.group());
Run Code Online (Sandbox Code Playgroud)

输出:

123-456-789-112-3
1234567891123
Run Code Online (Sandbox Code Playgroud)


Jon*_*n M 5

试试这个:

Pattern.compile("\\d(-?\\d){12}")
Run Code Online (Sandbox Code Playgroud)