1. OCAU Merchandise is available! Check out our 20th Anniversary Mugs, Classic Logo Shirts and much more! Discussion in this thread.
    Dismiss Notice

regex help - renaming files

Discussion in 'Programming & Software Development' started by bonox, Nov 30, 2021.

  1. bonox

    bonox Member

    Joined:
    Jul 14, 2001
    Messages:
    3,560
    Location:
    Sydney
    Hello smart people

    I've used youtubedl a lot in the past and it has appended a video id to the files. like

    filename-k4234fsa5r4.mp4
    or
    filename - subfilename-k4234fsa5r4.mp4

    The video id always begins with a dash.

    I've found progs like bulk rename utility but can't come up with a regular expression that will keep the extension and only trim from the last dash, not the first one it comes across.

    Have any of you come across a solution please?

    Thanks, b
     
  2. neRok

    neRok Member

    Joined:
    Aug 19, 2006
    Messages:
    4,316
    Location:
    Perth NOR
    rename.png

    Code:
    ^(.+)-[^-.]+(\.\w+)$
    ^ is start of string
    (.+) captures anything up until the next capture
    - captures -
    [^-.]+ captures anything that isn't a hyphen or dot up until the next capture. By making this capture not include hyphens, this ensures the previous hyphen was the last hyphen, as the previous capture anything will capture as many hyphens as it can.
    (\.\w+) captures the extension (a dot than and then any alphanumeric chars)
    $ is end of string

    If there could be spaces around the last hyphen, you will need to use the following code (` ?` will capture 0 or 1 spaces);
    Code:
    ^(.+) ?- ?[^-.]+\.\w+$
    PS: turns out you don't need to "save" the extension (no surrounding brackets in 2nd code). You could probably also safely remove the . in [^-.]
     
    Last edited: Nov 30, 2021
    bonox likes this.
  3. neRok

    neRok Member

    Joined:
    Aug 19, 2006
    Messages:
    4,316
    Location:
    Perth NOR
    Thinking about it some more, I first tested the regex on a website with the file extension, but if you don't tick Include Ext. in the program (unticked is default), then you can remove that portion. So the best code is probably;
    Code:
    ^(.+) ?- ?[^-]+$
     
    bonox likes this.
  4. OP
    OP
    bonox

    bonox Member

    Joined:
    Jul 14, 2001
    Messages:
    3,560
    Location:
    Sydney
    Thanks very much neRok - you're a lifesaver and your help receives 1000 karma points.

    cheers, b
     
    slavewone likes this.

Share This Page

Advertisement: