1

Trying to do a regex match and replace for a specific pattern to rename files. Unfortunately I'm not very good using regex and would appreciate any help you can offer.

the pattern I'm looking to replace is.

(Conflicted copy * ) 

To explain I need to replace (Conflicted copy *) basically everything that matches the words "(Conflicted copy" pattern and anything between those words and the closing parentheses.

so for example. Book1 (Conflicted copy some junk here).xls to : Book1.xls

What regex would I use for that? To replace?

I've tried the following: pattern = "\([^\(]*\)";

Unfortunately that doesn't work as there are paths that have () in them.

(ie, C:\Some crap\1.(stuff)\book1 (Conflicted copy junk stuff).xls )

it will fail and rename the file to:

(C:\Some crap\1.\book1.xls) -> then error out because that path doesn't exist.

Any help would be greatly appreciated thank you guys.

3
  • Add the "Conflicted copy" into the regexp so it only matches that Commented May 14, 2017 at 17:22
  • @SamiKuhmonen - Thanks for replying. I would but I don't know exactly where to add it in. Again not familiar with regex. Commented May 14, 2017 at 17:26
  • 1
    \(Conflicted copy [^)]*\) probably will work. Commented May 14, 2017 at 17:28

1 Answer 1

2

As it's very easy to get file extension, you could use this regex to extract filename only :

[^\\]*(?=\s\(Conflicted copy)

then append original file extension.

This avoid the use of regex groups by using positive lookahead.

Explanation

[^\\]* Match anything but a \ (to exclude file path)

(?=\s\(Conflicted copy) followed by a whitespace and (Conflicted copy

Demo

Other solution using groups

The following regex will extract filename without (Conflicted copy ...) and file extension :

([^\\]*)(?=\s\(Conflicted copy).*?\)(\..*)$

Group 1 : filename

Group 2 : file extension

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Updated answer to exclude file paths

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.