Home > Back-end >  Get string of corresponding placeholder according to format string
Get string of corresponding placeholder according to format string

Time:12-18

How can I get strings of corresponding placeholder according to format string?

For example:

The format string is My name is %s, and I'm %d years old, and I have a string My name is Mike, and I'm 18 years old。How to get Mike and 18 according to the format string, which correspond to placeholder %s and %d separately?

CodePudding user response:

I would use a regular expression with two groups. One to match any non-whitespace after My name is ending with a comma, the other to match any consecutive digits after I'm and ending in years old. Like,

String str = "My name is Mike, and I'm 18 years old";
Pattern p = Pattern.compile("My name is (\\S ), and I'm (\\d ) years old");
Matcher m = p.matcher(str);
if (m.find()) {
    System.out.printf("name=%s,age=%d%n", m.group(1), 
            Integer.parseInt(m.group(2)));
}

Which outputs

name=Mike,age=18
  • Related