使用正则表达式反向匹配字符

onu*_*can 2 regex delphi

我需要一个正则表达式,匹配从指定位置到第一个字符的字符串反向.字符串是一些文件名.

  • 即时通讯使用Delphi 2010
  • 我的示例字符串是New Document.extension
  • 如果指定位置为4,则应匹配:新文档

您可以按照以下步骤从"New Document.extension"到"New docu":

  • 首先去除扩展.你最终得到"新文档"
  • 删除最后4个字符.你得到"新纪录片".

对于"This Is My Longest Document.ext1.ext2"示例:

  • 剥离扩展,最终得到:"这是我最长的Document.ext1"
  • 剥去最后4个字符.你得到:"这是我最长的文件."

Tim*_*ker 5

所以你希望整个字符串在最后一个点之前到达倒数第四个位置?没问题:

Delphi .NET:

ResultString := Regex.Match(SubjectString, '^.*(?=.{4}\.[^.]*$)').Value;
Run Code Online (Sandbox Code Playgroud)

说明:

^       # Start of string
.*      # Match any number of characters
(?=     # Assert that it's possible to match, starting at the current position:
 .{4}   # four characters
 \.     # a dot (the last dot in the string!) because...
 [^.]*  # from here one only non-dots are allowed until...
 $      # the end of the string.
)       # End of lookahead.
Run Code Online (Sandbox Code Playgroud)