从字符串模式中提取参数

时间:2017-01-10 13:13:54

标签: java json matcher

我有像这样的字符串模式

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

比我有这样的句子

String sentence = "Send Hi there to Jesus";

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

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

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

2 个答案:

答案 0 :(得分:3)

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

有没有办法从模板中获取捕获组名称,   没有硬编码和#34;消息&#34;和&#34;名称&#34; ?

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

答案 1 :(得分:-1)

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];
}