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

使用正则表达式验证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.

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

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置