tags:

views:

56

answers:

3

I have some text like this:

dagGeneralCodes$_ctl1$_ctl0

Some text

dagGeneralCodes$_ctl2$_ctl0

Some text

dagGeneralCodes$_ctl3$_ctl0

Some text

dagGeneralCodes$_ctl4$_ctl0

Some text

I want to create a regular expression that extracts the last occurrence of dagGeneralCodes$_ctl[number]$_ctl0 from the text above. the result should be: dagGeneralCodes$_ctl4$_ctl0

Thanks in advance
Wael

+3  A: 

This should do it:

.*(dagGeneralCodes\$_ctl\d\$_ctl0)

The .* at the front is greedy so initially it will grab the entire input string. It will then backtrack until it finds the last occurrence of the text you want.

Alternatively you can just find all the matches and keep the last one, which is what I'd suggest.

Also, specific advice will probably need to be given depending on what language you're doing this in. In Java, for example, you will need to use DOTALL mode to . matches newlines because ordinarily it doesn't. Other languages call this multiline mode. Javascript has a slightly different workaround for this and so on.

cletus
I would also suggest grabbing everything using something like `/dagGeneralCodes$_ctl[0-9]$_ctl0/` and then grabbing the last one.
Thomas Owens
re DOTALL mode: Ruby calls it *multiline*, but everyone else calls it *DOTALL* or *single-line*, or a slight variation on one of those.
Alan Moore
+1  A: 

You can use:

[\d\D]*(dagGeneralCodes\$_ctl\d+\$_ctl0)

I'm using [\d\D] instead of . to make it match new-line as well. The * is used in a greedy way so that it will consume all but the last occurrence of dagGeneralCodes$_ctl[number]$_ctl0.

codaddict
Sorry I am new to regular expressions. [\d\D]*(dagGeneralCodes\$_ctl\d+\$_ctl0)Successfully deletes the contents of the string after the required dagGeneralCodes$_ctl4$_ctl0. But how to delete the text before dagGeneralCodes$_ctl4$_ctl0 and keep only dagGeneralCodes$_ctl4$_ctl0 as the result? Thanks in advanceWael
Wael
A: 

I really like using this Regular Expression Cheatsheet; it's free, a single page, and printed, fits on my cube wall.

Dean J