Skip to content
Advertisement

Regex to extract usernames/names from a string

I have strings that includes names and sometime a username in a string followed by a datetime stamp:

JavaScript

I want to extract the usernames from this string:

JavaScript

I have tried different regex patterns the closest I came to extract was following:

JavaScript

Using the following regex pattern:

JavaScript

Advertisement

Answer

You may get all text up to the first occurrence of -+digits+-:

JavaScript

If the number must be exactly 4 digits (say, if it is a year), then replace + with {4}:

JavaScript

See the regex demo

Details

  • ^ – start of string
  • .*? – any 0+ chars other than line break chars, as few as possible
  • (?=-d+-) – up to the first occurrence of - and 1+ digits (or, if d{4} is used, exactly four digits) and then - (this part is not added to the match value as the positive lookahead is a non-consuming pattern).

See Python demo:

JavaScript

Output:

JavaScript
Advertisement