[Solved] regex to find variables surrounded by % in a string


I believe you are looking for a regex pattern

(?<!%%)(?<=%)\w+(?=%)(?!%%)

That would find variables that are surrounded by a single % character on each side.

Test the regex here.


Java code:

final Pattern pattern = Pattern.compile("(?<!%%)(?<=%)\\w+(?=%)(?!%%)");
final Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
    System.out.println(matcher.group(0));
}

Test the Java code here.


UPDATE:

If you want to catch groups as requested in your comment below, use the following pattern:

(?<!%)(%)(\w+)(%)(?!%)

Test this pattern here.


…and Java code:

final Pattern pattern = Pattern.compile("(?<!%)(%)(\\w+)(%)(?!%)");
final Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
    System.out.println(matcher.group(1) + " | " + 
                       matcher.group(2) + " | " + 
                       matcher.group(3));
}    

Test this code here.

2

solved regex to find variables surrounded by % in a string