字符串 "Slot-Extraction"

String "Slot-Extraction"

我想查明给定的字符串 'b' 是否与字符串 'a' 的模式匹配。 此外,字符串 'a' 可能包含 placeholder/slots,而字符串 '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("<.*>", ".*"))

但我目前不知道如何以通用且可靠的方式实现此 "slot" 提取。

我将不胜感激 recommendations/hins。

您可以将第一个字符串中的 <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

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