How to use regex to match a name?

I am new to Python. I want to write a regular expression to check the name. My input line may contain az, AZ, 0-9, and '_', but it should start with az or AZ (not 0-9 and "_"). I want to write a regular expression for this. I tried, but nothing was perfect.

As soon as the input line follows the rules of regular expressions, I can continue further, otherwise discard this line.

+5
source share
3 answers

Here is the answer to your question:

Interpreting what you want _(not -), this should complete the task:

>>> tests = ["a", "A", "a1", "a_1", "1a", "_a", "a\n", "", "z_"]
>>> for test in tests:
...    print repr(test), bool(re.match(r"[A-Za-z]\w*\Z", test))
...
'a' True
'A' True
'a1' True
'a_1' True
'1a' False
'_a' False
'a\n' False
'' False
'z_' True
>>>

$; :

, , $ , \Z

>>> re.match(r"[a-zA-Z][\w-]*$","A")
<_sre.SRE_Match object at 0x00BAFE90>
>>> re.match(r"[a-zA-Z][\w-]*$","A\n")
<_sre.SRE_Match object at 0x00BAFF70> # WRONG; SHOULDN'T MATCH
>>>

>>> re.match(r"[a-zA-Z][\w-]*\Z","A")
<_sre.SRE_Match object at 0x00BAFE90>
>>> re.match(r"[a-zA-Z][\w-]*\Z","A\n")
>>> # CORRECT: NO MATCH

Fine Manual :

'$'
   โ€‹โ€‹ [ ], MULTILINE . foo "foo" "foobar", foo $ "foo". , foo. $ 'foo1\nfoo2\n' 'foo2 , ' foo1 MULTILINE; $ 'foo\n' () : .

\ Z
   .

=== - ===

>>> import string
>>> letters = set(string.ascii_letters)
>>> ok_chars = letters | set(string.digits + "_")
>>>
>>> def is_valid_name(strg):
...     return strg and strg[0] in letters and all(c in ok_chars for c in strg)
...
>>> for test in tests:
...     print repr(test), repr(is_valid_name(test))
...
'a' True
'A' True
'a1' True
'a_1' True
'1a' False
'_a' False
'a\n' False
'' ''
'z_' True
>>>
+5
>>> import re

>>> re.match("[a-zA-Z][\w-]*$","A")
<_sre.SRE_Match object at 0x00932E20>

>>> re.match("[a-zA-Z][\w-]*$","A_B")
<_sre.SRE_Match object at 0x008CA950>

>>> re.match("[a-zA-Z][\w-]*$","0A")
>>> 
>>> re.match("[a-zA-Z][\w-]*$","!A_B")
>>>

: OP, string cannot start from ( 0-9 and "_")., -, . \w

2. , \n, \Z $, .

+4

there is no way

import string
flag=0
mystring="abcadsf123"
if not mystring[0] in string.digits+"_":
    for c in mystring:
       if not c in string.letters+string.digits+"-":
           flag=1
    if flag: print "%s not ok" % mystring
    else: print "%s ok" % mystring
else: print "%s starts with digits or _" % mystring
-1
source

All Articles