I want to capture all numbers(any no.of digits) except the 10 digit numbers starting with 7.
71234567890 - should match
7123456789 - should not match
1234567890- should match
Use the pattern
/7\d{9}|(\d+)/
^^^^^^ MATCH 10-DIGIT NUMBER STARTING WITH SEVEN, DO NOT CAPTURE
^ --OR--
^^^^^ MATCH OTHER SEQUENCES OF DIGITS AND DO CAPTURE
This will match the 10-digit number starting with 7 but not capture it; otherwise, it will match the sequence of digits and capture it.
Now
'7123456789'.match(regexp)
["7123456789", undefined]
'1234567890'.match(regexp)
["1234567890", "1234567890"]
In other words, the captured string will be found in the second element of the array returned by match
.
If you want to anchor this to the beginning and end of the string, then
/^7\d{9}$|(^\d+$)/
You could also do this with a negative look-ahead, as suggested in the comments, but it's not needed here and could be a bit of a stretch for beginning regexpers.
(?:(?:^|\D)(7\d{1,8}|7\d{10,})(?:\D|$))
看演示
In order to get any number of digits except a string of 10 digits starting with '7'
you'd have to special case the '7'. There is really no way around it.
The fastest way is a pure regex solution, since the engine stays inside
running c++ engine code and does not interact with the host language.
There are two ways, either anchored or mid-string.
Anchored: ^(?:7(?!\\d{9}$)|[012345689])\\d*$
( number string is the overall match, ie in capture group 0 )
^ # Beginning of string
(?: # Cluster, get first digit
7 # '7'
(?! \d{9} $) # not followed by nine more digits
| # or
[012345689] # Any digit except '7' (i.e. [^\D7])
) # End cluster
\d* # Get optional remaining digits
$
Mid-string: (?:^|\\D)((?:7(?!\\d{9}(?:\\D|$))|[012345689])\\d*)
( number string is in capture group 1 )
(?: ^ | \D ) # Beginning of string or not a digit
( # (1 start), The number
(?: # Cluster, get first digit
7 # '7'
(?! # Assertion, not followed by nine more digits
\d{9}
(?: \D | $ ) # (forces no more/less than nine) digits
)
| # or
[012345689] # Any digit except '7' (i.e. [^\D7])
) # End cluster
\d* # Get optional remaining digits
) # (1 end)
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.