Reputation: 73
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
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 classUpvotes: 1
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