How to write a regular expression to check whether an input is an identifier or not?

0 votes
I have an identifier function that gets a string from a file and tests it to make sure that it's a valid identifier. So how do I write a regular expression to confirm the same?
Aug 8 in Python by Arvind
• 2,520 points
8 views

1 answer to this question.

0 votes

As per the documentation, an identifer can be defined as - identifier ::= (letter|"_") (letter | digit | "_")*

So the regular expression is  - ^[^\d\W]\w*\Z. You can refer the following code to understand a bit more.

import re
identifier = re.compile(r"^[^\d\W]\w*\Z", re.UNICODE)

tests = [ "c", "b11", "_z1", "1q", "da$%@%", "xx yy", "pp_ww", "vv\n" ]
for test in tests:
    result = re.match(identifier, test)
    print("%r\t= %s" % (test, (result is not None)))
The output will be like

'c' = True

'b11' = True

'_z1' = True

'1q' = False

'da$%@%' = False

'xx yy' = False

'pp_ww' = True

'vv\n' = False
answered Aug 8 by Neel
• 2,450 points

Related Questions In Python

0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12 in Python by Nymeria
• 3,500 points
53 views
0 votes
1 answer

How to check whether something is a variable or a function in Python?

Suppose you have a variable defined in ...READ MORE

answered Jul 30 in Python by Arvind
• 2,520 points
14 views
0 votes
1 answer

How to print a message or the error if a file is not found?

To print the message that file is not ...READ MORE

answered Jan 2 in Python by Omkar
• 67,290 points
24 views
0 votes
2 answers

How to check whether a string contains alphabets or number in Python?

By using isAlpha () to check whether ...READ MORE

answered Jul 13 in Python by Sheik janibasha
48 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 169 views
+4 votes
6 answers
0 votes
1 answer

how to check whether a string starts with a particular word?

For this, you can use the built-in ...READ MORE

answered Jul 17 in Python by Neel
• 2,450 points
17 views
0 votes
1 answer

How to check if a given string matches a particular pattern in Python?

You can use re module of python ...READ MORE

answered Jul 3 in Python by Neel
• 2,450 points
28 views