I am working on regular expression python, I came across this problem.
A valid mobile number is a ten digit number starting with a 7,8 or 9. my solution to this was :
if len(x)==10 and re.search(r'^[7|8|9]+[\d+]$',x):
for which i was getting error. later I changed it to
if len(x)==10 and re.search(r'^[7|8|9]+\d+$',x):
for which all test cases passed. I want to know what the difference between using and not using []
for \\d+
in regex ?
Thanks
[\\d+]
= one digit ( 0-9
) or +
character.
\\d+
= one or more digits.
You could also do:
if re.search(r'^[789]\d{9}$', x):
letting the regex handle the len(x)==10
part by using explicit lengths instead of unbounded repetitions.
I think a general explanation about []
and +
is what you need.
[]
will match with a single character specified inside.
Eg: [qwe]
will match with q
, w
or e
.
If you want to enter an expression inside []
, you need to use it as [^ expression]
.
+
will match the preceding element one or more times. Eg: qw+e
matches qwe
, qwwe
, qwwwwe
, etc...
Note: this is different from *
as *
matches preceding element zero or more times. ie qw*e
matches qe
as well.
\\d
matches with numerals. (not just 0-9
, but numerals from other language scripts as well.)
我不知道复杂性,但这也有效:
if (len(x)==10 and "789"==x[1:4]):
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.