jweinst1
11/18/2015 - 7:41 AM

Group of methods that scan strings of words and extract the first or last word.

Group of methods that scan strings of words and extract the first or last word.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;

public class classify {
    public static void main(String[] args) {
        System.out.println(isoneword("ok?"));
    }
    //checks for question mark at tail of the string.
    public static boolean isquestion(String phrase) {
        Pattern question = Pattern.compile("^.*[?]$");
        Matcher findq = question.matcher(phrase);
        return findq.matches();
    }
    //gets the first word in a string.
    public static String getfirstword(String phrase) {
        Pattern temp = Pattern.compile("^([a-z]+) .*$");
        Matcher first = temp.matcher(phrase);
        if (first.find()) {
            return first.group(1);
        }
        return "no match";
    }
    //gets the last word in a string
    public static String getlastword(String phrase) {
        Pattern temp = Pattern.compile("^.* ([a-z]+)$");
        Matcher last = temp.matcher(phrase);
        if (last.find()) {
            return last.group(1);
        }
        return "no match";
    }
    //determines if a string consists of a single word
    public static boolean isoneword(String phrase) {
        Pattern temp = Pattern.compile("^[a-z!?.]+$");
        Matcher word = temp.matcher(phrase);
        return word.matches();
    }
}