0

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
0

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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

You want

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

2 Comments

Notes: quantifier is not needed, it will match-exactly-one without. Assumes standard 26-letter alphabet.
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.
2

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

RegexBuddy

RegexBuddy

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.