Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String "Slot-Extraction"

I want to find out if a given String 'b' matches the pattern of String 'a'. Furthermore, the String 'a' may contain placeholder/slots, while String 'b' contains the actual values, which should be extracted.

Example:

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"

Expected Results:

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

To determine if a and b matches, I proceed as follows:

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

But I currently have no clue how to implement this "slot"-extraction in a generic and robust way.

I would be grateful for any recommendations/hins.

like image 323
Euestros Avatar asked Jun 26 '26 19:06

Euestros


1 Answers

You can replace tokens like this <name> with (.*) from your first string to form capture groups and then create a Pattern using the grouped string. Then you can use the second string to match the pattern and if it matches, then you can access all the groups to retrieve the data from groups.

Here is the initial code which I think should work and can be updated as per your other needs to make it further robust.

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");
    }
}

Prints,

Both string matches
NAME = Ben
CITY = New York

Let me know if this is what you were looking for and works for you.

like image 66
Pushpesh Kumar Rajwanshi Avatar answered Jun 29 '26 08:06

Pushpesh Kumar Rajwanshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!