Search code examples
javaregexprefix

Regex prefix, capture only odd number of instances?


I want to capture all mutually exclusive occurrences of strings inside two percentages "%". If its between two percentages, it will be flagged as a variable for replacement in my parsing process.

So if I have this input string

TLA%HRN%767%BRN%DFS

It should only return "HRN" and "BRN", not "HRN","767",and "BRN".

I don't want the 767 because it steals the percentage characters from HRN and BRN. I guess I only want to match where there is an odd number of percentage characters in the prefix.

Here is my regex work in progress. It captures the three instances, not just the two I want.

(?<=\b[A-Za-z1-9]+%).+?(?=%)

How do I capture only an odd number of percentage character occurrences in the prefix?


Solution

  • You can use this regex for matching:

    %[^%]+%
    

    Reason why it works because once % is consumed in %HRN% trailing % isn't available to return 767.

    Regex Demo