FP55
FP55

Reputation: 89

regular expression replace all except captured expression

I'm trying to use a regular expression to find everything except for the data I don't want to replace. I'm then wanting to replace everything except for the found expression.

My match is to find all words that start with "CN=" and ends with 12 characters after. I'm currently using the logic (!?CN=)\w{12}. It finds the two occurrences in the string. However, I'm wanting to find everything but these two occurrences and find everything else and replace everything else with an empty value so that I just have the two CN= word values.

The attached image shows my testing and results. I'm wanting the reverse affect.

image

Thanks, Fred

Upvotes: 1

Views: 79

Answers (1)

trincot
trincot

Reputation: 350365

You could use .* to capture whatever comes before a match, and add $ (end-of-input) as alternative for CN=\w{12}:

.*?($|CN=\w{12})

Replace with just the captured groups:

$1

Demo on Java regex tester

NB: I did not add the !? as you wrote ...words that start with "CN=". If you really need to keep the exclamation mark before CN=, then you should add it to the regular expression.

Upvotes: 2

Related Questions