我有一个非常长的字符串,我想解析子字符串“ISBN”后面出现的数字值。但是,这个13位数字的分组可以通过“ - ”字符进行不同的排列。示例:(这些都是有效的ISBN)123-456-789-123-4
,或或OR 12-34-56-78-91-23-4
。本质上,我想在潜在的ISBN上使用正则表达式模式匹配器来查看是否存在有效的13位ISBN。我如何“忽略”“ - ”字符,所以我可以只用\d{13}
模式的正则表达式?我的功能:用正则表达式提取ISBN
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;
}
我的建议是只替换'-'什么也没有。然后使用您的ISBN检查功能。如果它是正确的,你可以使用你需要的任何一个。 –
一些很好的正则表达式的答案,我肯定会用一个,因为它会赶上所有有效ISBN格式 - 但我只是想指出的是,在ISBN的破折号不要随意插入;只有某些组合是有效的。 (当然,你不是试图验证数字的形式,只是得到数字) –