Regular Expressions Help

A swapping-ground for Regular Expression syntax

Regular Expressions Help

Postby Xenokroy » Sun Dec 11, 2011 1:45 am

Hi,

I am quite new to regular expressions. I have started to read a bit about it and they are more involved than I anticipated. Perhaps someone out there can help me. I have a group of files i am attempting to rename the files have one of two formats.

AAA_BBBBB_CCCCCCC

or

AAA_CCCCCCC

The number of characters in A, B or C is not consistent; the underscores are always present.

I want to end up with this.

CCCCCCC_AAA_BBBBB

or

CCCCCCC_AAA

Any help on developing the regular expression to do this would be most appreciated.

Thanks in advance
Xenokroy
 
Posts: 2
Joined: Sun Dec 11, 2011 1:41 am

Re: Regular Expressions Help

Postby Glenn » Sun Dec 11, 2011 6:32 pm

There are many examples similar to this in the forum.
In any case, the pattern you have shown in your files is such that you want the part of the filename that is after the last underscore swapped to the front. Some may have 2 underscores, some one.
We can use a regex such as:
(.+)_(.+)

To grab the last (right most) underscore we can take advantage of the fact the normal regex (.+) is greedy and first matches the entire string. Then it works backwards (backtracks) from the end until it can match the _ and takes the first _ it finds which will be the right hand one. It captures the last piece after that in the second (.+) which is \2, the second captured group.
Now the first (.+) contains everything up to the last underscore, and it is the first captured group \1.
(Putting parentheses around sections of the match cause it to be captured and given names \1, \2, etc counting the groups of parentheses from left to right. These captured groups can then be used in the replace. This is one of the advantages of Regex)

Replace with:
\2_\1

There are other ways of doing this, and would require modification if the data assumptions are changed.

Cheers,
Glenn
Last edited by Glenn on Mon Dec 19, 2011 10:35 pm, edited 1 time in total.
Glenn
 
Posts: 28
Joined: Fri Apr 14, 2006 4:53 pm
Location: Winnipeg, Canada

Re: Regular Expressions Help

Postby Xenokroy » Mon Dec 19, 2011 10:18 pm

Glen,

thanks for the help.

In particular thank you for the why this is the correct RexExp syntax. I have never used it before and am learning. Most of the guides I found were great, but gave me more than I wanted or was ready to figure out just yet. Your explanation was clear and helped me understand why the attempts I had made failed to work correctly.

Thanks again,
-Roy
Xenokroy
 
Posts: 2
Joined: Sun Dec 11, 2011 1:41 am


Return to Regular Expressions