gpt4 book ai didi

java - 字符串 "Slot-Extraction"

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:06:00 26 4
gpt4 key购买 nike

我想查明给定的字符串“b”是否与字符串“a”的模式相匹配。此外,字符串“a”可能包含占位符/槽,而字符串“b”包含应提取的实际值。

例子:

String a = "Hello my name is <NAME> and I am from <CITY>"
String b = "Hello my name is Ben and I am from New York"

预期结果:

-> b matches a
-> NAME = "Ben"
-> CITY = "New York"

为了确定 a 和 b 是否匹配,我按以下步骤进行:

b.matches(a.replaceAll("<.*>", ".*"))

但我目前不知道如何以通用且稳健的方式实现这种“插槽”提取。

如果有任何建议/提示,我将不胜感激。

最佳答案

您可以像这样替换标记 <name>(.*)从您的第一个字符串形成捕获组,然后创建一个 Pattern使用分组的字符串。然后您可以使用第二个字符串来匹配模式,如果它匹配,那么您可以访问所有组以从组中检索数据。

这是我认为应该可以工作的初始代码,可以根据您的其他需求进行更新,以使其更加健壮。

public static void main(String[] args) {
matchAndExtract("Hello my name is <NAME> and I am from <CITY>", "Hello my name is Ben and I am from New York");
}

public static void matchAndExtract(String s1, String s2) {
List<String> placeHolderNames = new ArrayList<>();

Pattern p1 = Pattern.compile("(?<=<)[^<>]+(?=>)");
Matcher m1 = p1.matcher(s1);
while (m1.find()) {
placeHolderNames.add(m1.group());
}

Pattern p2 = Pattern.compile(s1.replaceAll("<.*?>", "(.*)"));
Matcher m2 = p2.matcher(s2);
if (m2.matches()) {
System.out.println("Both string matches");
for (int i = 0; i < m2.groupCount(); i++) {
System.out.println(placeHolderNames.get(i) + " = " + m2.group(i + 1));
}
} else {
System.out.println("Both string doesn't match");
}
}

打印,

Both string matches
NAME = Ben
CITY = New York

让我知道这是否是您正在寻找的并且适合您。

关于java - 字符串 "Slot-Extraction",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55300980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com