How to Match a Word with a Certain Amount of Characters using Regular Expressions in Python



Python


In this article, we show how to match a word with a certain amount of characters in Python using regular expressions.

Let's say we want the user to enter in a username and the username has to be between 2 and 25 characters in length.

We can use a regular expression that must be within 2 and 25 characters.

We will write a regular expression that accepts only input that is 2-25 characters in length long.

We then use an if statement, that if the input is not in this range, that it is invalid input. If the input is in this range of 2-25 characters, then it is valid.

So let's now go over this code below.



So let's now go over this code.

re is the module in Python that allows us to use regular expressions. So we first have to import re in our code, in order to use regular expressions.

After this, we have a variable, firstname, which contains the string that we want to search using regular expressions.

We then have the variable, regex, which is set equal to, "[A-Za-z]{2,25}"

What this regular expression does is it looks for a name of alphabetical characters that are 2 to 25 characters in length.

We then use an if statement to print out valid name if the regular expression is met or invalid name if the regular expression is not met.

Below is the same exact code but with a first name of 1 character, which is too short for a first name.



Because the first name, according to our regular expression must be between 2 and 25 characters and 'J' is 1 character, it is invalid. Thus, we get invalid output.

And this is how we can match a word with a certain amount of characters in Python using regular expressions.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...