如何使用正则表达式或其他技术解析此字符串?
答
最基本的方法是使用字符串及其索引来玩。
对于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]);
答
什么我明白,你瓦纳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
答
在Java 1.4中:
String s="hello example >> hai man";
String[] b=s.split(">>");
System.out.println(b[1].trim());
答
您可以使用正则表达式为:
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));
}
}
答
考虑以下几点:
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;
}
@Tassos:“家庭作业标签。 ..现在不鼓励,“](http://meta.stackoverflow.com/q/10812)但@subha,请(一如既往)遵循[一般指导原则](http://tinyurl.com/so-hints):陈述任何特殊限制,展示您迄今为止所尝试的内容,并询问特别令您困惑的是什么。 – 2010-11-11 13:10:02