在Java中,以下是最好的实现方式。我有两个输入字符串。
this is a good example with 234 songs
this is %%type%% example with %%number%% songs
我需要从字符串中提取类型和数字。
在这种情况下,答案是type="a good"和number="234"
谢谢
您可以使用正则表达式来完成:
import java.util.regex.*;
class A {
public static void main(String[] args) {
String s = "this is a good example with 234 songs";
Pattern p = Pattern.compile("this is a (.*?) example with (\\d+) songs");
Matcher m = p.matcher(s);
if (m.matches()) {
String kind = m.group(1);
String nbr = m.group(2);
System.out.println("kind: " + kind + " nbr: " + nbr);
}
}
}
Pattern p = Pattern.compile("this is (.+?) example with (\\d+) songs");
Matcher m = p.matcher("this is a good example with 234 songs");
boolean b = m.matches();
String in = "this is a good example with 234 songs";
String pattern = "this is %%type%% example with %%number%% songs";
Pattern p = Pattern.compile(pattern.replaceAll("%%(\w+)%%", "(\\w+)");
Matcher m = p.matcher(in);
if (m.matches()) {
for (int i = 0; i < m.groupsCount(); i++) {
System.out.println(m.group(i+1))
}
}
Geos, 我建议使用Apache Velocity库http://velocity.apache.org/。它是一个字符串模板引擎。你的例子看起来像这样
this is a good example with 234 songs
this is $type example with $number songs
实现此功能的代码如下:
final Map<String,Object> data = new HashMap<String,Object>();
data.put("type","a good");
data.put("number",234);
final VelocityContext ctx = new VelocityContext(data);
final StringWriter writer = new StringWriter();
engine.evaluate(ctx, writer, "Example templating", "this is $type example with $number songs");
writer.toString();