質問

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?

役に立ちましたか?

解決

Description: It can be in two forms:

  1. Starts with numeric chars then there should be some chars, followed by any number of alpha-numeric chars are possible.
  2. Starts with alphabets, then some numbers, followed by any number of alpha-numeric chars are possible.

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>

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top