java – 从字符串模式中提取参数

我有这样的String模式

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

比我有这样一句话

String sentence = "Send Hi there to Jesus";

我想要的是将句子与模式匹配并返回类似的东西
具有句子参数的JsonObject:

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

这有什么简单的解决方案吗?

最佳答案 此单元测试通过组索引引用匹配的组(请注意附带的圆括号)来提取句子内容.如果模式与给定字符串匹配,则整个输入字符串为组0.在给定示例中,匹配的消息位于组索引1和索引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);
    }
}

Is there any way to get the capturing group name from the template,
without hardcoding “message” and “name” ?

ad-hoc解决方案可能是使用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;
}
点赞