How to replace last two characters?

Please check the FAQ (https://www.xyplorer.com/faq.php) before posting a question...
Post Reply
ak1pper
Posts: 3
Joined: 17 Apr 2024 07:52

How to replace last two characters?

Post by ak1pper »

Good morning!
I'm new here, and although I've been able to get by on my own so far, there's something that's resisting me. Using RegExp, how can I replace the last two characters of a file as well as the first two? I give an example:

Original:

Z8264519300.psd

How I want it to look:

Z8264519399.psd

As you can see, it would be changing the two 0's for two 9's.
Also, if I wanted to change the Z8 for a P7, how would you do it?

Thank you very much in advance. Have a great day guys.

highend
Posts: 13345
Joined: 06 Feb 2011 00:33
Location: Win Server 2022 @100%

Re: How to replace last two characters?

Post by highend »

Code: Select all

    $old = "Z8264519300.psd";
    $new = regexreplace($old, "(.*?)(\d{2})(\.[^.]+?)$", "$1" . "99" . "$3");
    // $new = "Z8264519399.psd"

    // ---

    $old = "Z8264519300.psd";
    $new = regexreplace($old, "^(.{2})(.*?)$", "P7" . "$2");
    // $new = "P7264519300.psd"
One of my scripts helped you out? Please donate via Paypal

ak1pper
Posts: 3
Joined: 17 Apr 2024 07:52

Re: How to replace last two characters?

Post by ak1pper »

highend wrote: 17 Apr 2024 08:08

Code: Select all

    $old = "Z8264519300.psd";
    $new = regexreplace($old, "(.*?)(\d{2})(\.[^.]+?)$", "$1" . "99" . "$3");
    // $new = "Z8264519399.psd"

    // ---

    $old = "Z8264519300.psd";
    $new = regexreplace($old, "^(.{2})(.*?)$", "P7" . "$2");
    // $new = "P7264519300.psd"
Brilliant.

One question, if I want to make several files at the same time, how would it be?
I'm looking for something like what I use in RegExp to remove the last 8 (or whatever) characters: ^(.*)(.{8})(\.[^.]+)$ > $1$3

Is there a way to do this to replace X last letters with others?

highend
Posts: 13345
Joined: 06 Feb 2011 00:33
Location: Win Server 2022 @100%

Re: How to replace last two characters?

Post by highend »

Code: Select all

    $items = <get SelectedItemsPathNames>;
    foreach($item, $items, <crlf>, "e") {
        $file = gpc($item, "file");
        $new  = regexreplace($file, "(.*?)(\d{2})(\.[^.]+?)$", "$1" . "99" . "$3");
        if ($file != $new) { renameitem($new, $item) };
    }
One of my scripts helped you out? Please donate via Paypal

ak1pper
Posts: 3
Joined: 17 Apr 2024 07:52

Re: How to replace last two characters?

Post by ak1pper »

Great, this is what I meant.

Thank you very much for your time.

Post Reply