2010-02-14 108 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