-1

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 ?

Alok Tiwari
  • 23
  • 1
  • 2
  • 9

2 Answers2

1

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.

Sattyaki
  • 376
  • 2
  • 9
  • 1
    The question isn't asking how to count the number of instances of a specific substring. And it isn't asking how to check if it contains a subsring either – musefan Nov 07 '17 at 10:19
  • i am not asking what is the position for string 009876.. i wan to extract only 009876 from the whole text .. i wants to eliminate all other .. sop i have source as 009876 and i wants to math this source with the given text.. if it matches then return that text... – Alok Tiwari Nov 09 '17 at 09:48
0

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")
        }
    }
}