输入以下数据:
图案:anyValue{variable1}otherValue{variable2}lastValue
值:anyValuehellootherValueworldlastValue
预期此输出
variable1: hello
variable2: world
我可以有任何带大括号的变量吗, 我想要一个使用正则表达式的例子,用Java或其他语言实现,
输入以下数据:
图案:anyValue{variable1}otherValue{variable2}lastValue
值:anyValuehellootherValueworldlastValue
预期此输出
variable1: hello
variable2: world
我可以有任何带大括号的变量吗, 我想要一个使用正则表达式的例子,用Java或其他语言实现,
您可以在Java中使用以下代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String pattern= "anyvalue{variable1}anyvalue{variable2}anyvalue{var3}";
String input = "anyvaluehelloanyvalueworldanyvaluesomething";
// Convert the pattern into a regular expression
String regex = pattern.replaceAll("\\{(.+?)\\}", "(?<$1>.*)");
Pattern r = Pattern.compile(regex);
Matcher m = r.matcher(input);
if (m.find()) {
// Get the names of the capture groups from the pattern
Pattern groupNamesPattern = Pattern.compile("\\(\\?<(.+?)>");
Matcher groupNamesMatcher = groupNamesPattern.matcher(regex);
// Print all the variables that were found
while (groupNamesMatcher.find()) {
String variableName = groupNamesMatcher.group(1);
String variableValue = m.group(variableName);
System.out.println(variableName + ": " + variableValue);
}
} else {
System.out.println("No match found.");
}
}
}
我基本上是将您的模式转换为模式中任何{VARIABLE_NAME}的命名组.据我所知,没有简单的方法来获得组的名称,所以您需要第二个正则表达式来获得这些名称作为您的输出.
然而,似乎有一些替代方案可以找到指定的组.如果你想寻找其他 Select ,你可以关注this thread,以找到这些组的名称.