开发者

Matching chars before last backslash using regex

I'm trying to make a Delphi project about renaming files, and I somehow found a regex to match all chars after last backslash for file names: [^\\]+$ at this address: Can you read backward in regex?. But I couldn't find a regex code to match all chars BEFORE last backslash (for path names).

I found following example but couldn't modify it for backslashes and all chars. [^/]+(?=/[^/]+$) Match folder name from url using regex

  • I'm using Delphi 2010

  • My regex engine is regex-directed (NFA)

  • My example string is

    D:\belgelerD\delphi_projects_renamer\12\test_files开发者_StackOverflow\Yeni Metin Belgesi.txt

  • I want it to match

    D:\belgelerD\delphi_projects_renamer\12\test_files\


Are you aware which delphi is full of Path manipulation procedures and functions?

for example in your case to get the D:\belgelerD\delphi_projects_renamer\12\test_files\ string from D:\belgelerD\delphi_projects_renamer\12\test_files\Yeni Metin Belgesi.txt you can use the ExtractFilePath function.


Looking first at your original regexp, [^\] matches anything but a backslash. Adding the plus after it matches one or more times. Finally the dollar at the end matches the end of the string. Thus this will match a sequence of characters which aren't backslashes, followed by the end of the string. As regular expressions are greedy it will capture everything from the last backslash to the end of the string.

To capture the inverse, i.e. everything before the last backslash you can do something like ^.+\\ which should capture everything from the start of the string (^) to the final backslash.

If you can use pattern match groups then you can use something like ^(.+)([^\]+)$ to match split the string into two parts, each of which will be stored as a different match group result.

Note: I'm not sure what Delphi's regexp engine is like so you may need to escape the brackets to make them work as group delimiters.


Not sure about Delphi regex syntax, but this regex matches everything before last backslash:

^.*(?=\\[^\\]+$


This pattern: ^(.*)([\\\/]) will give you this result:

matches:

  • 0: D:\belgelerD\delphi_projects_renamer\12\test_files\
  • 1: D:\belgelerD\delphi_projects_renamer\12\test_files
  • 2: \

This pattern: ^(.*[\\\/]) will give you this result:

matches:

  • 0: D:\belgelerD\delphi_projects_renamer\12\test_files\
  • 1: D:\belgelerD\delphi_projects_renamer\12\test_files\

Pattern 1 will give you everything before the last slash NOT including the last slash.
Pattern 2 will give you everything before the last slash including the last slash.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜