duandi4238 2016-12-21 20:46
浏览 1030
已采纳

使用正则表达式验证ISBN号

I need a regex to verify ISBN number entered by user.

ISBN must be a string contains only: [10 or 13 digits] and hyphens

I tried ^[\d*\-]{10}|[\d*\-]{13}$ but it doesn't work.

My regex only matches: 978-1-5661, 1-56619-90, 1257561035

It should returns the results below:

"978-1-56619-909-4 2" => false
"978-1-56619-909-4" => true
"1-56619-909-3 " => false
"1-56619-909-3" => true
"isbn446877428ydh" => false
"55 65465 4513574" => false
"1257561035" => true
"1248752418865" => true

I really appreciate any help.

  • 写回答

1条回答 默认 最新

  • doutenggu4070 2016-12-21 20:51
    关注

    You can use this regex with a positive lookahead:

    ^(?=(?:\D*\d){10}(?:(?:\D*\d){3})?$)[\d-]+$
    

    RegEx Demo

    (?=(?:\D*\d){10}(?:(?:\D*\d){3})?$) is a positive lookahead that ensures we have 10 or 13 digits in the input.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?