2010-02-14 86 views
4

在Java中执行以下操作的最佳方法是什么? 我有两个输入字符串java中的字符串解析

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

我需要从字符串中提取类型和数量。

答案在这种情况下为TYPE = “良好的”,并数= “234”

感谢

+0

我不明白你正在尝试做的?您是否试图提取“this is”和“example”之间的值? – Zinc 2010-02-14 17:26:32

回答

7

你可以用正则表达式做到这一点:

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

Java has regular expressions

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

如果第二个字符串是一个模式。你可以把它编译成正则表达式,如

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

如果您需要命名组也可以解析分组序号和名称之间的字符串模式和存储映射到一些地图

+0

他希望包含空格,\ w不会工作 – 2010-02-14 17:33:35

0

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

我认为他正在尝试做模板的“相反”。即给定输出字符串和模板提取生成输出的上下文。 – flybywire 2010-02-14 17:41:32