[英]Get string of corresponding placeholder according to format string
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?格式字符串是My name is %s, and I'm %d years old
,我有一个字符串My name is Mike, and I'm 18 years old
。如何根据格式字符串得到Mike
和18
,这分别对应占位符%s
和%d
?
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
.一个匹配My name is
以逗号结尾后的任何非空格,另一个匹配I'm
后以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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.