Finding the Nth Word in a File
-
OK, I am relatively new to Notepad++. I used to use it years ago for a lot of my programming, but it’s been ages since I’ve left the IT field. So please keep it Barney style for me.
Can someone explain if it’s possible to use Notepad++ find/highlight a particular word in a document. I don’t want to find and replace. I simply want to find it. For example, let’s say I pasted as simple text this sentence: “The quick red fox jumped over the lazy brown dog.”
I would like to enter somewhere find the 4th word, and have a result come back as “fox.”
- Is this possible? 2. Can it be done with any length of a document?
Thanks in advance,
Kris -
Well, you can at least approximate it by searching in Regular expression mode for:
\A\W*?(?:(\w+)(?:\W+|\z)){
N}
where N is desired word number.
But there are a lot of caveats about what characters make up a word – in the expression I used they are A thru Z, a thru z, 0 thru 9, and underscore.
And it will match the text from the beginning up to the word number of interest, not simply the word of interest. I’m sure it could be made fancier using
\K
in the expression to highlight only the word of interest, but then some math would have to be done, e.g. searching forN-1
instead ofN
.I won’t bother explaining how it works, since I don’t like talking to purple dinosaurs.
-
@Alan-Kilborn Haha! Thank you! Now for something even more fun. Where do I plug in this expression to perform the search?
Thanks again!
-
@Kristopher-Gill said in Finding the Nth Word in a File:
Where do I plug in this expression to perform the search?
When I said:
searching in Regular expression mode
I meant: Go to the Search menu and select Find …. Then put the expression I gave in the Find what box, select Regular expression in the Search mode area, then press Find All in Current Document.
-
@Alan-Kilborn Did exactly as I was looking for/intended. Thank you again for your help. This is great.
-
Hello, @kristopher-gill, @alan-kilborn and all,
Personally, I would use the following regexes, having the same concept of
Nth word
:-
The regex
\A\W*(?:\w+\W+){
N-1}\K\w+
finds/marks theNth
word, of any file containing, at least, N words -
The regex
(\A|\R\h*\R)\W*(?:\w+\W+){
N-1}\K\w+
finds/marks theNth
word, of any paragrah containing, at least, N words -
The regex
(?-s)^[^\w\r\n]*(?:\w+[^\w\r\n]+){
N-1}\K\w+
finds/marks theNth
word, of any line containing, at least, N words
Notes :
-
The
Regular expression
radio button is selected -
The
Wrap around
option is checked -
In case of a
Find Next
search, move to beginning of file, first (Ctrl + Home
) -
Use, either, the
Find Next
, theFind All in Current Document
, theFind All in All Opened Documents
or theMark All
button
Best Regards,
guy038
-