diff --git a/hertzbeat-common/src/main/java/org/apache/hertzbeat/common/util/JexlCommonFunction.java b/hertzbeat-common/src/main/java/org/apache/hertzbeat/common/util/JexlCommonFunction.java index bc4b1bcf2f3..18ec5085e4e 100644 --- a/hertzbeat-common/src/main/java/org/apache/hertzbeat/common/util/JexlCommonFunction.java +++ b/hertzbeat-common/src/main/java/org/apache/hertzbeat/common/util/JexlCommonFunction.java @@ -19,11 +19,12 @@ package org.apache.hertzbeat.common.util; +import java.util.regex.Matcher; import java.util.regex.Pattern; /** * the common function for jexl str equals, match, contains, etc. - * sys:now() + * sys:now() */ public class JexlCommonFunction { @@ -94,5 +95,27 @@ public boolean matches(String str, String regex) { } return Pattern.compile(regex).matcher(str).matches(); } - + + /** + * Extracting groups from strings using regular expressions + * @param str Input string + * @param regex regular expression pattern + * @param groupIndex The group index to be extracted (0 for the entire match, 1 for the first group) + * @ return The extracted string does not match and returns null + */ + public String group(String str, String regex, int groupIndex) { + if (str == null || regex == null) { + return null; + } + try { + Matcher matcher = Pattern.compile(regex).matcher(str); + if (matcher.find() && groupIndex <= matcher.groupCount()) { + return matcher.group(groupIndex); + } + } catch (Exception e) { + // Return null when regular expression is incorrect + } + return null; + } + } diff --git a/hertzbeat-common/src/test/java/org/apache/hertzbeat/common/util/JexlTest.java b/hertzbeat-common/src/test/java/org/apache/hertzbeat/common/util/JexlTest.java index fa502f8f6b4..9cec79e44e3 100644 --- a/hertzbeat-common/src/test/java/org/apache/hertzbeat/common/util/JexlTest.java +++ b/hertzbeat-common/src/test/java/org/apache/hertzbeat/common/util/JexlTest.java @@ -501,6 +501,19 @@ void testMatchesFunctionWithRegexNotMatch() { Assertions.assertFalse((Boolean) o); } + @Test + void testGroupFunctionWithRegexWithGroupIndex() { + Map functions = Maps.newLinkedHashMap(); + functions.put("sys", new JexlCommonFunction()); + jexlBuilder.namespaces(functions); + JexlEngine jexl = jexlBuilder.create(); + JexlContext context = new MapContext(); + context.set("x", "akka.tcp://flink@hdp-hadoop3:45534/user/rpc/taskmanager_0"); + JexlExpression e = jexl.createExpression("sys:group(x, '@([^:]+):',1)"); + Object o = e.evaluate(context); + Assertions.assertEquals("hdp-hadoop3", o); + } + @Test void testMatchesFunctionWithRegexAndSpace() { Map functions = Maps.newLinkedHashMap();