Going to the <n>th occurrence on a line

Find, replace, find in files, replace in files, regular expressions

Going to the <n>th occurrence on a line

Postby sklad2 » Wed Feb 18, 2009 12:35 pm

I have data delimited by ^
Sample:

12^eeyryr^^1122^122121^qtyewtwewt^dgheg37636^^^^s^

I would like to find the <n>th occurence of the ^
For example to find the first ^
I used \^ reg expressions and perl. I happily went to each ^
Next I tried to go to every 2nd ^ and tried \^{2}
But that did not do what I want. You regex guys are probable laughing now.
Next I tried \^[^\^]{2}
That failed too.
Also note on some "fields" they are empty like ^^ or more together.

All help is appreciated.
User avatar
sklad2
Advanced User
Advanced User
 
Posts: 58
Joined: Thu Mar 08, 2007 12:00 am

Re: Going to the <n>th occurrence on a line

Postby pietzcker » Wed Feb 18, 2009 3:12 pm

This is difficult with regular expressions, especially if you only want the nth ^ to be highlighted. It wouldn't be a problem to match everything up until the nth ^, but that isn't what you need, I guess. If Perl were to support variable-length lookbehind, it would be easy to do, but sadly, that's a feature Perl doesn't have.

I see two options:

Search for all the text leading up to the nth ^ using the Perl regex ^(?:[^\^]*\^){n-1}[^\^]* - then the cursor will be placed right before the nth ^. (Of course you have to replace n-1 by an actual number)

If you want to select the nth ^, you could use the approach above in combination with a macro:

InsertMode
ColumnModeOff
HexOff
Key HOME
PerlReOn
Find RegExp "^(?:[^\^]*\^){4}[^\^]*"
Key RIGHT ARROW
StartSelect
Key LEFT ARROW

to select the fifth ^ in this case.

A completely different idea:

You said that these are data delimited by ^. You could use the command "Convert to fixed columns" in the Column menu and specify ^ as the separator character. This will align all the separators throughout the file, ensuring that the nth ^ is always in the same column. Perhaps that's also a possibility?
User avatar
pietzcker
Master
Master
 
Posts: 241
Joined: Sun Aug 22, 2004 11:00 pm

Re: Going to the <n>th occurrence on a line

Postby sklad2 » Thu Feb 19, 2009 12:52 pm

Thanks for the great info!!!!!

I am very interested in all of the options you presented. :D

All of them are fantastic!!!!
User avatar
sklad2
Advanced User
Advanced User
 
Posts: 58
Joined: Thu Mar 08, 2007 12:00 am


Return to Find/Replace/Regular Expressions