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, 2019 in Python by Arvind
• 3,050 points
3,735 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, 2019 by Neel
• 3,020 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, 2019 in Python by Nymeria
• 3,560 points
11,286 views
0 votes
0 answers

How to check whether a variable is a class or not?

I was wondering how to check whether ...READ MORE

Nov 24, 2022 in Python by sarit
• 1,830 points
421 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, 2019 in Python by Arvind
• 3,050 points
1,931 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, 2019 in Python by Omkar
• 69,220 points
2,866 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,069 views
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, 2019 in Python by Neel
• 3,020 points
708 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, 2019 in Python by Neel
• 3,020 points
1,200 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP