A.Taylor
A.Taylor

Reputation: 73

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.

Upvotes: 3

Views: 491

Answers (2)

The fourth bird
The fourth bird

Reputation: 163487

You might also use a capturing group, first matching until the last occurrence of : and then capture in group 1 matching 16 characters other than :

^.*:([^:]{16})

Explanation

  • ^ Start of string
  • .*: Match the last occurrence of :
  • ([^:]{16}) Capture group 1, match 16 chars other than : using the negated character class

Regex demo

Upvotes: 1

Ryszard Czech
Ryszard Czech

Reputation: 18631

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

Upvotes: 3

Related Questions