Johannes Wentu
Johannes Wentu

Reputation: 989

Regex to find strings that contain a certain text only once

I need to find all the lines in a file where a certain text appears exactly once. The text is an occurrence of something like:

##somethingVariable##

that is, all the time a string is between ## and ##

I am using the following RegEx:

(?<!.*<CAPTURE>.*)(?<CAPTURE>##[^#]*##)(?!.*<CAPTURE>.*)

I find what i need with

##[^#]*## 

i capture it and name it and i say to find it only if it is not preceded or followed by the same capture text. I also tried with different combinations of ^$ before and after and some .* before and there but it doesnt work. What am i doing wrong?

Examples:

inThisString##THIS##appreasJustOnceAndIWantToFindIt
inThisString##THAT##AppreasTwiceAndIDoNOTWantToFind##THAT##case

Upvotes: 1

Views: 103

Answers (1)

anubhava
anubhava

Reputation: 785166

You can use lookahead based regex like this:

^(?:(?!##).)*(##[^#]*##)(?!.*?\1).*$

RegEx Demo

This will match first input in your example but won't match the second one.

Upvotes: 1

Related Questions