tags:

views:

97

answers:

5

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

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

You want

if re.search('[A-Za-z0-9]+', i):
    print i
Paul McMillan
Notes: quantifier is not needed, it will match-exactly-one without. Assumes standard 26-letter alphabet.
pst
Yea, the `+` is not needed.
hasen j
Removed the +. It's habit since an expression like that invariably becomes more complex in my own code, and I usually do want the + if there's anything else to it.
Paul McMillan
+1  A: 

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

Bart Kiers
+2  A: 

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.

pst
To get rid of the double \\, you can use a raw string: r'[^_\W]'
Andre Miller
It just occured to me that `[^_\\]` looks like a pirate
hasen j
That would also match string consisting solely of punctuation marks.
Bart Kiers
How ? \W matches punctuation marks, so its negation will not.
Matthieu M.
A: 

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
...
ghostdog74
A: 
Kalmi