Search code examples
regexregex-lookarounds

Regex - characters after delimiter, limited to a number


I am trying to put together some regex to get only the first 16 characters after the :

blahblahblah:fakeblahfakeblahfakeblahfakeblah

I came up with /[^:]*$ but that matches everything after the colon and if I try to trim from there its actually starting at the last character.


Solution

  • Use

    (?<=:)[^:]{16}(?=[^:]*$)
    

    See proof

    Explanation

    --------------------------------------------------------------------------------
      (?<=                     look behind to see if there is:
    --------------------------------------------------------------------------------
        :                        ':'
    --------------------------------------------------------------------------------
      )                        end of look-behind
    --------------------------------------------------------------------------------
      [^:]{16}                 any character except: ':' (16 times)
    --------------------------------------------------------------------------------
      (?=                      look ahead to see if there is:
    --------------------------------------------------------------------------------
        [^:]*                    any character except: ':' (0 or more
                                 times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
        $                        before an optional \n, and the end of
                                 the string
    --------------------------------------------------------------------------------
      )                        end of look-ahead