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

标签 java json matcher

我有一个像这样的字符串模式

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

我有这样一句话

String sentence = "Send Hi there to Jesus";

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

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

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

最佳答案

此单元测试通过组索引引用匹配的组(注意封闭的圆括号)来提取句子内容。如果模式与给定的字符串匹配,则整个输入字符串为组 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);
    }
}

Is there any way to get the capturing group name from the template, without hardcoding "message" and "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;
}

关于java - 从字符串模式中提取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41569731/

相关文章:

Java DecimalFormat 格式化零

java - 在android中根据端口(网络发现)在本地网络上查找机器

java - Play 框架 2.0.4 Java : impossible to convert ArrayList of POJOs in JsonNode

json - Cloudformation 找不到区域 Opsworks 堆栈

javascript - Mocha/Chai 测试预期与实际对象数组

java - 在模式匹配器中使用变量

java - 如何在java程序中使用它后将其标记为死行或已使用

java主机头攻击

javascript - 如何检查javascript中来自服务器的数据中是否存在 key ?

java - 如何用正则表达式匹配 1 或 2 个字符