简体   繁体   中英

Regex: Find everything after a period, before the last slash

I've found some similar regex questions, but I'm striking out at turning those answers into what I'm trying to do. I have a string like this:

Y:\Path\sub path\name_of_folder.microphones.flac24\trackname01.flac

I want to return "flac24"

The number of periods in the name_of_folder will vary. I've figured out how to isolate the text between the last two slashes, but I can't seem to now get the part after the last period:

(?<=\\)[^\\]*(?=\\[^\\]*$)

Thanks!

For a regex, I would do:

\.([^.\\]+)\\[^\\]+$

Demo

Since you tagged this Python, you might also consider just using Pathlib

from pathlib import PureWindowsPath 

p=PureWindowsPath(r'Y:\Path\sub path\name_of_folder.microphones.flac24\trackname01.flac')

>>> p.parts[-2].split('.')[-1]
flac24

You can use

\\[^\\]*\.([^\\]*)\\[^\\]*$

See the regex demo . Details :

  • \\ - a \ char
  • [^\\]* - zero or more chars other than \ as many as possible
  • \. - a . char
  • ([^\\]*) - Group 1: zero or more chars other than \ char
  • \\ - a \ char
  • [^\\]* - zero or more chars other than \ char
  • $ - end of string.

See the Python demo :

import re
regex = r"\\[^\\]*\.([^\\]*)\\[^\\]*$"
x = "Y:\\Path\\sub path\\name_of_folder.microphones.flac24\\trackname01.flac"
match = re.search(regex, x)
if match:
    print(match.group(1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM