Extract an ISBN with regex

后端 未结 7 1933
终归单人心
终归单人心 2021-01-14 01:01

I have an extremely long string that I want to parse for a numeric value that occurs after the substring \"ISBN\". However, this grouping of 13 digits can be arranged differ

7条回答
  •  情歌与酒
    2021-01-14 01:29

    • Alternative 1:

      pattern.matcher(ISBN.replace("-", ""))
      
    • Alternative 2: Something like

      Pattern.compile("(\\d-?){13}")
      

    Demo of second alternative:

    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());
    

    Output:

    123-456-789-112-3
    1234567891123
    

提交回复
热议问题