Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use regex to verify an ISBN number

Tags:

regex

php

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.

like image 519
Louis Tran Avatar asked Dec 24 '22 22:12

Louis Tran


1 Answers

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.

like image 57
anubhava Avatar answered Dec 26 '22 17:12

anubhava