Skip to content
Advertisement

How to extract words of constant length form a paragraph?

I’m trying to extract the words form a paragraph/string. I searched it out many where but didn’t find relative material. I want to extract words of length 4 from

“I want to have alot of moneys when I am older probably e1X2”

I’m trying to extract using

List<String> words = new ArrayList<String>();
        String s  = "I want to have alot of moneys when I am older probably.";
        Pattern p = Pattern.compile("[a-zA-Z']{4,}");
        Matcher m = p.matcher(s);
        while (m.find()) {
            words.add(m.group());
        }

    System.out.println(words);

The output which am I getting right now

[want, have, alot, moneys, when, older, probably]

but the output must be

[want, have, alot, when]

Advertisement

Answer

The simpler way to get the result :

List<String> words=new ArrayList<String>(); 
    String s="I want to have alot of of moneys when I am older probably";
    String str[]=s.split(" ");
    for(int i=0;i<str.length;i++)
    {
        if(str[i].length()==4)
            words.add(str[i]);
    }
    System.out.print(words);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement