How to write a regular expression in Python that accepts alphabets, numbers and a few selected special characters(,.-|;!_?)?

1.6k views Asked by At

A Regular Expression in Python that accepts letters,numbers and only these special characters (,.-|;!_?).

I have tried solving the problem through the following regular expressions but it didn't work:

'([a-zA-Z0-9,.-|;!_?])$'
'([a-zA-Z0-9][.-|;!_?])$'

Can someone please help me write the regular expression.

4

There are 4 answers

0
Tagc On BEST ANSWER

I think the following should work (tested on RegExr against Foo123,.-|;!_?):

^[\w,.\-|;!_?]*$

In your regular expressions, you forget to escape the '-' character, which is interpreted as a range of characters to match against.

0
ettanany On

Try this (you should escape - like this \-):

^[a-zA-Z0-9,.\-|;!_?]+$

+ to prevent matching empty strings, to allow them, you can use * instead.

Examples:

>>> import re
>>> 
>>> re.match('^[a-zA-Z0-9,.\-|;!_?]+$', '12.0')
<_sre.SRE_Match object at 0x00000000027EB850>
>>> re.match('^[a-zA-Z0-9,.\-|;!_?]+$', '')
>>>
>>> re.match('^[a-zA-Z0-9,.\-|;!_?]+$', 'test!?')
<_sre.SRE_Match object at 0x00000000027EB7E8>
0
lorenzog On

You could use \w (bonus: unicode and locale support!):

matches any alphanumeric character and the underscore; this is equivalent to the set [a-zA-Z0-9_]

See Python's documentation. Also, you might want to use a raw string when specifying your regular expression pattern:

m = re.match(r'[\w,.-|;!?]+', your_string)

Notice the use of + (repeat once or more). You also used $ to match the end of the string but I did not include it in mine. YMMV.

0
DomeTune On

Use this for only one character:

'[a-zA-Z0-9,.\-|;!_?]' or '[\w,.\-|;!_?]'

Use this for all characters:

'[a-zA-Z0-9,.\-|;!_?]*' or '[\w,.\-|;!_?]*'

Use this for an equal check:

'^[a-zA-Z0-9,.\-|;!_?]*$' or '^[\w,.\-|;!_?]*$'