简体   繁体   中英

matching 8 or 9 digits using regex

I have what I think is a simple regex question - i'm fairly new to regex, so, i have it down about 90% (i think!) on this issue.

I need to match one of two strings (all digits) inside a text box.

 1. ####-####
 2. ########

so, first string is 9 characters, with the '-' in the middle. second string is 8 digits with no '-' in there.

what i got is:

/[\d]{4}-??[\d]{4}/

which works pretty well, BUT, since i have to allow for 9 characters because of the first option, this also validates ######### (9 digits), since the first 8 match the expression.

so, how do i do this?

I thought perhaps including [^\\d]? at the end would do it (optional, non digit, which would makes the 9th digits break the match), but, that didn't do...

Thanks for reading!

您需要添加行首和行尾标记,以确保仅此模式匹配。

/^[\d]{4}-?[\d]{4}$/

Use ^ and $ :

'00000000'.match(/^\d{4}-?\d{4}$/) // true
'0000-0000'.match(/^\d{4}-?\d{4}$/) // true
'000000000'.match(/^\d{4}-?\d{4}$/) // nil

^ matches the beginning of the string; $ matches the end. Without them, you're matching any substring. So your original regex would match a 20-digit string, for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM