开发者

Regular expression to match alphanumeric string

If string "x" contains any letter or number, print that string. How to do that using regular expressions? The code below is wrong

开发者_C百科
if re.search('^[A-Z]?[a-z]?[0-9]?', i):
        print i


re — Regular expression operations

This question is actually rather tricky. Unfortunately \w includes _ and [a-z] solutions assume a 26-letter alphabet. With the below solution please read the pydoc where it talks about LOCALE and UNICODE.

"[^_\\W]"

Note that since you are only testing for existence, no quantifiers need to be used -- and in fact, using quantifiers that may match 0 times will returns false positives.


You want

if re.search('[A-Za-z0-9]+', i):
    print i


I suggest that you check out RegexBuddy. It can explain regexes well.

Regular expression to match alphanumeric string

Regular expression to match alphanumeric string

Regular expression to match alphanumeric string


[A-Z]?[a-z]?[0-9]? matches an optional upper case letter, followed by an optional lower case letter, followed by an optional digit. So, it also matches an empty string. What you're looking for is this: [a-zA-Z0-9] which will match a single digit, lower- or upper case letter.

And if you need to check for letter (and digits) outside of the ascii range, use this if your regex flavour supports it: [\p{L}\p{N}]. Where \p{L} matches any letter and \p{N} any number.


don't need regex.

>>> a="abc123"
>>> if True in map(str.isdigit,list(a)):
...  print a
...
abc123
>>> if True in map(str.isalpha,list(a)):
...  print a
...
abc123
>>> a="##@%$#%#^!"
>>> if True in map(str.isdigit,list(a)):
...  print a
...
>>> if True in map(str.isalpha,list(a)):
...  print a
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜