Home>

I want to make a regular expression for the following rules.

  • Half-width alphanumeric characters (lowercase) and "_ (half-width underscore)"
  • 5 to 30 characters
  • The first character is [a-z] only
  • Half-width underscore is prohibited at the end of the sentence
  • Continuous half-width underscore is prohibited

Form input I plan to use it to limit form input.
If i can't specify only the pattern attribute, I'm thinking of using javascript.

I was a beginner in programming, and I tried to google with "regular expressions" etc., but I could not understand it immediately because it was deep, but I will take this opportunity to master regular expressions!

  • Answer # 1

    We have not verified it in detail.
    It is an image that is loosely verified first and then excluded later.

    [
      'aaaa',
      '_aaaa',
      'a__a__a',
      'a_a_a_a_',
      '0aaaaa',
      'aaaaaaaaa1aaaaaaaaa2aaaaaaaaa3a',
      'abcde',
      'a_b_c_d_e'
    ] .forEach (str =>{
      let chk_reg =/(? = ^ [a-z0-9_] {5,30} $) (?! ^ [0-9_]. + |. + __ |. + _ $) /;
     console.log (str, "=", chk_reg.test (str));
    });

  • Answer # 2

    Continuous half-width underscore is prohibited

    Other than that, it's okay if you can understand only the character class, the number of iterations, and the beginning and end of the string.

    Continuous half-width underscore is prohibited

    Since you have to use a function that is a little difficult to make into one regular expression including up to
    match (4 conditions) and not match (last condition)It is good to write code like.

  • Answer # 3

    Another solution is a pattern that can be used for anything other than checking the length.

    ^ [a-z] (?: _? [A-z0-9]) * $

    This will match one or more strings that meet the conditions (other than the string length), so you can check the length of the successfully matched string separately.

  • Answer # 4

    [a-z] (?: [a-z0-9] | _ (?! _)) {3,28} [a-z0-9]

Related articles