I have a string:
hello example >> hai man
How can I extract the "hai man" using Java regex or another technique?
I have a string:
hello example >> hai man
How can I extract the "hai man" using Java regex or another technique?
See run: 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));
}
}
The most basic way is to play with character from String and its index.
For the hello example >> hai man use
String str ="hello example >> hai man";
int startIndex = str.indexOf(">>");
String result = str.subString(startIndex+2,str.length()); //2 because >> two character
I think it clears up basic idea.
There are lots of tricks you can parse using
Another simpler way is :
String str="hello example >> hai man";
System.out.println(str.split(">>")[1]);
Consider the following:
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;
}