1

I am fairly new to regex and I'd greatly appreciate some guidance.
I have quite a huge text file and I'd like to bookmark the lines of my keywords but only their first instances.

For example:


Apples are delicious.
I like turtles.
He is tall.
She is beautiful.
Go to hell!
Turtles are smart.
These are the world's most beautiful buildings.
Apples are good for your health.
The Hungarian flag is a horizontal tricolour of red, white and green.
Turtles are reptiles.
You are very clever.
Hungarian is a difficult language.
Bananas and apples are usually cheap.


If I make a regex (apple|turtle|hungarian), I get 8 bookmarked lines but in the above-mentioned example, I only need the first occurences, so I want to bookmark only the following sentences:

  • Apples are delicious.
  • I like turtles.
  • The Hungarian flag is a horizontal tricolour of red, white and green.

Is there a way to do this?

Thank you in advance.

2
  • Use the bookmark feature on the search results
    – DavidPostill
    Apr 27, 2017 at 8:25
  • Maybe I have misunderstood your comment but I'm not sure what is your suggestion. I'm using the bookmark feature. My problem is that I only need the first results. My text contains 80-90000 lines and I have more than 100 keywords so doing this manually is not an option sadly. Apr 27, 2017 at 8:39

1 Answer 1

0

Nice question, I had to go and learn some new Regex tricks to get to an answer :)
I don't think there is a way of solving this in just one regex statement for all your words at the same time. My solution is on a word per word basis. For 100 keywords... this could still be managable.

So, here it is

\A^.*?(?<!apple).*?\Kapple

Let me break that down...

We are looking for the first occurence of apple

apple

But without the word apple in front of it, so we need to use the Negative Lookbehind feature

(?<!apple)apple

But, there could be other characters, and newlines in between, so, select the option ". matches newline" and use:

(?<!apple).*?apple

The .* needs to be non-greedy, I'm not entirely sure why... :)

New, because of this issue (I had to go and ask to figuere it out ;) ), we need to anchor our regex to the beginning of the file:

\A^(?<!apple).*?apple

\A is the "permanent start of string", in notepad++ it matches the beginning of the file.
We also have to add ^, to anchor it to the first line of the file.

Of course there could be characters in between the start of the file and the first occurence of apple, so

\A^.*?(?<!apple).*?apple

And, we are only interested in the location of apple, not the entire pattern, so we use \K to Keep The Text Matched So Far out of The Overall Regex Match

\A^.*?(?<!apple).*?\Kapple

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .