I want to extract a particular word from a text using Java
. Is it possible
e.g. :
String str = "this is 009876 birthday of mine";
I want to get '009876' from above text in Java
. Is this possible ?
I want to extract a particular word from a text using Java
. Is it possible
e.g. :
String str = "this is 009876 birthday of mine";
I want to get '009876' from above text in Java
. Is this possible ?
You can do it easily by regex. Below is an example:
import java.util.regex.*;
class Test {
public static void main(String[] args) {
String hello = "this is 009876 birthday of mine";
Pattern pattern = Pattern.compile("009876");
Matcher matcher = pattern.matcher(hello);
int count = 0;
while (matcher.find())
count++;
System.out.println(count); // prints 1
}
}
If you want to check if the text contains the source string (e.g. "009876") you can do it simply by contains method of String as shown in below example:
public static String search() {
// TODO Auto-generated method stub
String text = "this is 009876 birthday of mine";
String source = "009876";
if(text.contains(source))
return text;
else
return text;
}
Let me know if any issue.
You can do it like this:
class ExtractDesiredString{
static String extractedString;
public static void main(String[] args) {
String hello = "this is 009876 birthday of mine";
Pattern pattern = Pattern.compile("009876");
if (hello.contains(pattern.toString())) {
extractedString = pattern.toString();
}else{
Assert.fail("Given string doesn't contain desired text")
}
}
}