Ungreedy regex matching in sublime text 2

40 Views Asked by At

I'm fairly familiar with regex, but it seems I'm not so good at doing regex in sublime text 2, what I thought should work seems to match but too greedily.

I have a file with lots of mv commands in it like the one below, and I wanting add an additional command above it to create the directory where the file is to be moved to. So for the below example the mkdir command would be mkdir --parents --verbose '/path/to/dir2';

mv --no-clobber --verbose '/path/to/dir1/file1.zip' '/path/to/dir2/file2.zip';

I tried this regex which I was sure would be perfectly fine, but it matches the whole line and not just the sections I would like to match.

Sublime regex search

mv --no-clobber --verbose '(.*?).zip' '(.*?)/(.*?).zip';

Sublime regex replace

mkdir --parents --verbose '$2';
mv --no-clobber --verbose '$1.zip' '$2\/$3.zip';

Edit: Just to clarify the first (.*?) matches the whole line, the subsequent (.*?) match nothing.

1

There are 1 best solutions below

0
anubhava On

You have few unwanted capture groups and there is no need to use .*?.

You can search using this regex:

mv --no-clobber --verbose '[^']+' '(.+)/[^/.]+\.zip';

and replace using:

$0\nmkdir --parents --verbose '$1';

Here $0 is back-reference for the full match of mv command.

Output:

mv --no-clobber --verbose '/path/to/dir1/file1.zip' '/path/to/dir2/files2.zip';
mkdir --parents --verbose '/path/to/dir2';

You can also search using \K (match reset):

mv --no-clobber --verbose '[^']+' '(.+)/[^/.]+\.zip';\K

and replace with:

\nmkdir --parents --verbose '$1';