正则表达式 - 定界符后的字符,限于数字

Regex - characters after delimiter, limited to a number

我正在尝试将一些正则表达式放在一起以获得 前 16 个字符 :

blahblahblah:fakeblahfakeblahfakeblahfakeblah

我想到了 /[^:]*$ 但这匹配冒号后的所有内容,如果我尝试从那里 trim 它实际上从最后一个字符开始。

使用

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

proof

说明

--------------------------------------------------------------------------------
  (?<=                     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

您也可以使用捕获组,首先匹配直到最后一次出现 :,然后在组 1 中捕获匹配 :

以外的 16 个字符
^.*:([^:]{16})

说明

  • ^ 字符串开头
  • .*: 匹配最后一次出现的 :
  • ([^:]{16}) 捕获 组 1,使用否定字符 class
  • 匹配 : 以外的 16 个字符

Regex demo