TIMEX
TIMEX

Reputation: 271594

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

if re.search('^[A-Z]?[a-z]?[0-9]?', i):
        print i

Upvotes: 0

Views: 8210

Answers (5)

Tarnay Kálmán
Tarnay Kálmán

Reputation: 7056

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

RegexBuddy

RegexBuddy

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342263

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
...

Upvotes: 0

Paul McMillan
Paul McMillan

Reputation: 20107

You want

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

Upvotes: 2

Bart Kiers
Bart Kiers

Reputation: 170138

[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.

Upvotes: 1

user166390
user166390

Reputation:

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.

Upvotes: 4

Related Questions