java中的字符串解析

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

Java有正则表达式 :

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

如果第二个字符串是一个模式。 你可以把它编译成regexp,就像一个

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

如果需要命名组,还可以解析字符串模式,并将组索引和名称之间的映射存储到某个Map中

Geos,我建议使用Apache Velocity库http://velocity.apache.org/ 。 它是字符串的模板引擎。 你的例子看起来像

 this is a good example with 234 songs this is $type example with $number songs 

执行此操作的代码看起来像

 final Map data = new HashMap(); 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();