How to clean the details with regex?

What regex expression can I use to ensure this pattern match (see details of the question)?

  • Conditions: 1. First character is between a-z (lowercase) 2. Last character must be either a-z (lowercase) or 0-9 3. Can have underscores anywhere in between 4, Can have nothing outside of a-z (lowercase), 0-9 or underscores in the whole string

  • Answer:

    The naive expression ^[a-z][a-z_0-9]*[a-z0-9]$ fails to match for the empty string, or single-character lowercase alphabetical strings. A correct answer is: ^[a-z]?((?<=.)[a-z_0-9])*((?<=.)[a-z0-9])$ where (?<=x) is a positive lookbehind on x. This regular expression is constructed as follows: ^ — match the start of the string; unnecessary in some languages and contexts [a-z]? — match zero or one alphabetical character; this is the first character, if any ((?<=.)[a-z_0-9])* — match zero or more alphabetical, numeric, or underscore characters, as long as they are not the first character in the string ((?<=.)[a-z0-9] — matches the last character, as long as it is not the first character in the string $ — match the end of the string; unnecessary in some contexts If you want to exclude the empty string as a match, you can use this expression: ^[a-z]([a-z_0-9](?=.))*[a-z0-9]?$

William Chargin at Quora Visit the source

Was this solution helpful to you?

Other answers

^(?:[a-z](?:[a-z_0-9]*[a-z0-9])?)?$ Here's a diagram: http://www.regexper.com/#%5E(%3F%3A%5Ba-z%5D(%3F%3A%5Ba-z_0-9%5D*%5Ba-z0-9%5D)%3F)%3F%24 This will match: Empty string Single character "a-z" Two character "a-z" followed by "a-z0-9" Three or more character, following all of your conditions. If you don't want to match empty string: ^[a-z](?:[a-z_0-9]*[a-z0-9])?$ Here's a diagram: http://www.regexper.com/#%5E%5Ba-z%5D(%3F%3A%5Ba-z_0-9%5D*%5Ba-z0-9%5D)%3F%24

Lee Byron

[a-z]I got my homework answer off the Internet.[a-z_0-9]*[a-z0-9]

Tony Li

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.