[英]How to parse this string using regex or another technique?
我有一個字符串:
hello example >> hai man
如何使用Java正則表達式或其他技術提取“ hai man”?
您可以將正則表達式用作:
String str = "hello example >> hai man";
String result = str.replaceAll(".*>>\\s*(.*)", "$1");
參見運行: 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));
}
}
最基本的方法是使用String及其索引中的字符進行播放。
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]);
在Java 1.4中:
String s="hello example >> hai man";
String[] b=s.split(">>");
System.out.println(b[1].trim());
考慮以下:
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;
}
我了解到您想消除這個問題,您可以做一些類似的事情
string myString = "hello example >> hai man";
string mySecondString = mystring.Replace("hai man", "");
您將只看到hello example >>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.