Retrieving Arguments from a String Template

I have a string template like this

String pattern = "Send {{message}} to {{name}}";

Than I have a suggestion like this

String sentence = "Send Hi there to Jesus";

I want to combine sentences with a template and return something like JsonObject, which has arguments from the sentence:

{"message": "Hi there", "name": "Jesus"}

Are there simple solutions for this?

+4
source share
2 answers

unit test ( ) . , - 0. message 1 name 2. .

@RunWith(Parameterized.class)
public class Snippet {

    private final String testSentence;
    private final String[][] expectedResult;



    public Snippet(String testSentence, String[][] expectedMessages) {
        this.testSentence = testSentence;
        this.expectedResult = expectedMessages;
    }

    private String[][] extractSentenceContent(String sentence) {
        Pattern pattern = Pattern.compile("Send\\s([\\p{Alpha}\\s]+)\\sto\\s([\\p{Alpha}\\s]+)");
        Matcher matcher = pattern.matcher(sentence);

        String[][] result;

        if(matcher.matches()) {
            result = new String[][] {{"message", matcher.group(1)}, {"name", matcher.group(2)}};
        } else {
            result = null;
        }
        return result;
    }

    @Test
    public void testRegex(){

        String[][] actualResult = extractSentenceContent(testSentence);

        TestCase.assertTrue(Arrays.deepEquals(expectedResult, actualResult));
    }



    @Parameters
    public static Iterable<?> getTestParameters(){

        Object[][] parameters = {
                {"Send Hi there to Jesus", new String[][] {{"message", "Hi there"}, {"name", "Jesus"}}}
        };
        return Arrays.asList(parameters);
    }
}

, hardcoding "message" "name"?

String.format , :

private String[][] extractSentenceContent(String sentence, String captureGroupA, String captureGroupB) {
    String pattern = String.format("^Send\\s(?<%s>[\\p{Alpha}\\s]+)\\sto\\s(?<%s>[\\p{Alpha}\\s]+)$", captureGroupA, captureGroupB);

    Matcher matcher = Pattern.compile(pattern).matcher(sentence);

    String[][] result;

    if(matcher.matches()) {
        result = new String[][] {
            {captureGroupA, matcher.group(captureGroupA)}, 
            {captureGroupB, matcher.group(captureGroupB)}
        };
    } else {
        result = null;
    }
    return result;
}
+3
i= sentence.length();

while(sentence[i] != " "){
    i--;
}

i++;

for(intj=0;j<i;j++)
    name[j]= sentence[j];
}

for(int k = 5;k<(sentence.length()-i-3);k++){
    message[k] = sentence[k];
}
-1

Source: https://habr.com/ru/post/1666378/


All Articles