Reputation: 363
Below I have the following regex:
alphanumeric = compile('^[\w\d ]+$')
I'm running the current data against this regex:
Tomkiewicz Zigomalas Andrade Mcwalters
I have a separate regex to identify alpha characters only, yet the data above still matches the alphanumeric criteria.
Edit: How do I stop the only alpha data matching with the regex above?
Upvotes: 1
Views: 2080
Reputation: 3446
Use a lookahead to assert the condition that at least one alpha and at least one digit are present:
(?=.*[a-zA-Z])(?=.*[0-9])^[\w\d ]+$
The above RegEx utilizes two lookaheads to first check the entire string for each condition. The lookaheads search up until a single character in the specified range is found. If the assertion matches then it moves on to the next one. The last part I borrowed from the OP's original attempt and just ensures that the entire string is composed of one or more lower/upper alphas, underscores, digits, or spaces.
Upvotes: 1
Reputation: 58251
Description: It can be in two forms:
Demo:
>>> an_re = r"(\d+[A-Z])|([A-Z]+\d)[\dA-Z]*"
>>> re.search(an_re, '12345', re.I) # not acceptable string
>>> re.search(an_re, 'abcd', re.I) # not acceptable string
>>> re.search(an_re, 'abc1', re.I) # acceptable string
<_sre.SRE_Match object at 0x14153e8>
>>> re.search(an_re, '1abc', re.I)
<_sre.SRE_Match object at 0x14153e8>
Upvotes: 3