2010-11-11 53 views
2

我有一個字符串:如何使用正則表達式或其他技術解析此字符串?

hello example >> hai man 

我怎樣才能提取「海人」使用Java正則表達式或其他技術?

+1

@Tassos:「家庭作業標籤。 ..現在不鼓勵,「](http://meta.stackoverflow.com/q/10812)但@subha,請(一如既往)遵循[一般指導原則](http://tinyurl.com/so-hints):陳述任何特殊限制,展示您迄今爲止所嘗試的內容,並詢問特別令您困惑的是什麼。 – 2010-11-11 13:10:02

回答

1

最基本的方法是使用字符串及其索引來玩。

對於hello example >> hai man使用

String str ="hello example >> hai man"; 
int startIndex = str.indexOf(">>"); 
String result = str.subString(startIndex+2,str.length()); //2 because >> two character 

我認爲這清除了基本思路。

有很多技巧的,你可以使用

另一種更簡單的方式解析是:

 String str="hello example >> hai man"; 
    System.out.println(str.split(">>")[1]); 
-2

什麼我明白,你瓦納eleminate這ü可以做一些事情像

string myString = "hello example >> hai man"; 
string mySecondString = mystring.Replace("hai man", ""); 

您將只獲得hello example >>

+0

爲什麼1- ?? ...... ...... – Singleton 2010-11-11 11:33:20

+1

我相信你誤會了這個問題。 – 2010-11-11 13:12:31

1

在Java 1.4中:

String s="hello example >> hai man"; 
String[] b=s.split(">>"); 
System.out.println(b[1].trim()); 
4

您可以使用正則表達式爲:

String str = "hello example >> hai man"; 
String result = str.replaceAll(".*>>\\s*(.*)", "$1"); 
2

請參見運行:http://www.ideone.com/cNMik

public class Test { 
    public static void main(String[] args) { 
     String test = "hello example >> hai man"; 

     Pattern p = Pattern.compile(".*>>\\s*(.*)"); 
     Matcher m = p.matcher(test); 

     if (m.matches()) 
      System.out.println(m.group(1)); 
    } 
} 
0

考慮以下幾點:

public static void main(String[] args) { 
     //If I get a null value it means the stringToRetrieveFromParam does not contain stringToRetrieveParam. 
     String returnVal = getStringIfExist("hai man", "hello example >> hai man"); 
     System.out.println(returnVal); 

     returnVal = getStringIfExist("hai man", "hello example >> hai man is now in the middle!!!"); 
     System.out.println(returnVal); 
    } 

    /**Takes the example and make it more real-world like. 
    * 
    * @param stringToRetrieveParam 
    * @param stringToRetrieveFromParam 
    * @return 
    */ 
    public static String getStringIfExist(String stringToRetrieveParam,String stringToRetrieveFromParam){ 
     if(stringToRetrieveFromParam == null || stringToRetrieveParam == null){ 
      return null; 
     } 
     int index = stringToRetrieveFromParam.indexOf(stringToRetrieveParam); 
     if(index > -1){ 
      return stringToRetrieveFromParam.substring(index,index + stringToRetrieveParam.length()); 
     } 
     return null; 
    }