比较Java字符串中的多个差异

时间:2015-01-13 12:46:44

标签: java

我有一个字符串模板,如下所示:

This position is reserved for <XXXXXXXXXXXXXXXXXXXXXXXXXXX>. Start date is <XXXXXXXX>

填写,这可能看起来像这样(保留固定宽度):

This position is reserved for <JOHN SMITH                 >. Start date is <20150228>

如何在单个字符串中提取多个差异?如果我可以避免,我不想将整个模板引擎用于一项任务。

2 个答案:

答案 0 :(得分:10)

您可以尝试这样的正则表达式:

  public static void main(String[] args) {
    String s = "This position is reserved for <JOHN SMITH                 >. Start date is <20150228>";
    Pattern p = Pattern.compile(".*?<(.*?)>.*<(.*?)>");
    Matcher m = p.matcher(s);
    while(m.find()){
        System.out.println("Name : " +m.group(1).trim());
        System.out.println("Date : " +m.group(2).trim());
    }

}

O / P:

Name : JOHN SMITH
Date : 20150228

答案 1 :(得分:1)

如果模板可能被修改,您可以使用格式模式。

String expected = "This position is reserved for <JOHN SMITH                 >. Start date is <20150228>";
System.out.println(expected);
// define the output format
String template = "This position is reserved for <%-27s>. Start date is <%s>";
String name = "JOHN SMITH";
String startDate = "20150228";
// output the values using the defined format
System.out.println(String.format(template, name, startDate));