I'm trying to match the inner content of the first braces in Java only if the template with braces occurs first. For instance:
{FOO}/bar/{BAR} -> "FOO"
/{FOO}/bar/{BAR} -> null
{BAR}/foo/{FOO} -> "BAR"
I was tested the following regex which seemed to work ^{(.*?)}
in the online regex testers; however, when I try to do this in Java as ^\\{(.*?)}
it fails. I suspect it has something to do with the braces being misinterpreted. Currently, the Java regex doesn't match any of the above strings.
protected Optional<String> getHostVariableNameFromTemplate(String template) {
final String REGEX = "^\\{([^}]*)}";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(template);
return (matcher.matches()) ? Optional.of(matcher.group(0)) : Optional.empty();
}
@Test // fails
public void getHostVariableNameFromTemplate_shouldReturnFirstVariable() {
String template = "{SOME_HOST}/foo/{fooId}/bar/{barId}?filter=foobar";
Optional<String> host = testObj.getHostVariableNameFromTemplate(template);
assertTrue(host.isPresent());
assertEquals("SOME_HOST", host.get());
}