skip to Main Content

The following program I wrote

var textRegEx = /.{1,3}/g;
var text = "AUZ01A1";
var woohooMatch = text.match(textRegEx);
var finalResult = woohooMatch.join(' - ')

console.log(finalResult);

gives the output as:

Output:

AUZ - 01A - 1

I want the output to be AUZ - 01 - A1. How do I alter textRegEx to achieve this? I tried (2, 3} and some other things, but it doesn’t work. I am new to both javascript and regex. Can you please help?

3

Answers


  1. You can use groups () to match pattern of 3,2,2 characters:

    var text = "AUZ01A1";
    var textRegEx = /(.{3})(.{2})(.{2})/;
    var woohooMatch = text.match(textRegEx);
    var [ , ...matches] = woohooMatch;
    var finalResult = matches.join(' - ');
    
    
    console.log(finalResult);
    Login or Signup to reply.
  2. Separate cases of 6/7, 8 and other by a simple switch statement:

    function format(string) {
      switch (string.length) {
        case 6:
        case 7:
          return string.match(
            /^(.{2,3})(.{2})(.{2})$/
          ).slice(1).join(' - ');
        break;
        case 8:
          return string.match(
            /^(.{7})(.)$/
          ).slice(1).join(' - ');
        default:
          return string;
      }
    }
    

    Or, if you prefer a tricky regex in a terse function:

    function format(string) {
      const match = string.match(/^(?=.{6,8}$)(?:.{7}|.{2,3})(?=(.{1}$|.{2})(.{2})?$)/);
      return match ? (match[2] ? match : match.slice(0, -1)).join(' - ') : string;
    }
    

    Explanation for the regex, the rest is left as an exercise for the reader:

    ^                # Match at the beginning of string
    (?=.{6,8}$)      # a string of 6, 7 or 8 characters long, which consists of
    (?:.{7}|.{2,3})  # a capturing group of either 7 or 2 to 3 characters
    (?=              # followed by
      (.(?:.|$))     # a second capturing group of a character followed by another or the end of string
      (.{2})?        # and an optional capturing group of two characters.
      $              # right before the end of string.
    )                #
    

    Try it on regex101.com.

    Try it:

    function format1(string) {
      switch (string.length) {
        case 6:
        case 7:
          return string.match(
            /^(.{2,3})(.{2})(.{2})$/
          ).slice(1).join(' - ');
        break;
        case 8:
          return string.match(
            /^(.{7})(.)$/
          ).slice(1).join(' - ');
        default:
          return string;
      }
    }
    
    function format2(string) {
      const match = string.match(/^(?=.{6,8}$)(?:.{7}|.{2,3})(?=(.{1}$|.{2})(.{2})?$)/);
      return match ? (match[2] ? match : match.slice(0, -1)).join(' - ') : string;
    }
    
    // Test cases
    const strings = [...'1234567890'].map(
      (_, i, a) => a.slice(0, i + 1).join('')
    );
    
    console.log(strings.map(format1));
    console.log(strings.map(format2));
    .as-console-wrapper {
      max-height: 100% !important;
    }
    Login or Signup to reply.
  3. For your format, you can use an alternation with capture groups.

    Then in the result, remove the full match and join the capture groups with -

    Note that a . matches any character. If you only want to match uppercase chars or digits, you can use a character class [A-Zd]

    ^(?:(.{2,3})(..)(..)|(.)(.{7}))$
    

    Explanation

    • ^ Start of string
    • (?: Non capture group for the alternatives
      • (.{2,3})(..)(..) 3 capture groups, where the first group has 2 or 3 chars
      • | Or
      • (.)(.{7}) 2 capture groups, where the first has a single char and the second group 7 chars
    • ) Close the non capture groups
    • $ End of string

    Regex demo

    const regex = /^(?:(.{2,3})(..)(..)|(.)(.{7}))$/gm;
    const s = `AUZ01A
    AUZ01A1
    AUZ01A11`;
    
    for (const match of s.matchAll(regex)) {
      const result = match.slice(1)
        .filter(Boolean)
        .join(' - ');
      console.log(result);
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search