0

I have a string template that looks something like this:

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

Filled out, this might look like this (fixed width is preserved):

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

How can I extract multiple differences in a single String? I don't want to use an entire templating engine for one task if I can avoid it.

3
  • What output expected? Commented Jan 13, 2015 at 12:50
  • 1
    The output expected is shown. Commented Jan 13, 2015 at 12:51
  • Why don't use substring() then? For you example s.substring(31, 58) will return JOHN SMITH and so on. Commented Jan 13, 2015 at 12:57

2 Answers 2

10

You can try regex like this :

  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
Sign up to request clarification or add additional context in comments.

Comments

1

If the template might be modified you could use a format pattern.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.