Say there is a sentence
That Sam-I-am
Two words end in the same sequence “am”, where the second sequence is the last word.
I need to write a regular expression to match such a sentence, where the sequence could be any string of letters.
The language is Java. What I don’t quite understand is how one would match something within a sentence and ignore the rest.
It is a prep question for a Java test.
Thank you.
This is code I’m using to test
public static void doMatching(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String pattern, s;
System.out.print("Pattern: ");
pattern = in.readLine();
while (!pattern.equals("quit")){
System.out.print("String: ");
s = in.readLine();
System.out.println(Pattern.matches(pattern, s));
System.out.print("Pattern: ");
pattern = in.readLine();
}
} catch (IOException e){
System.out.println("Error!");
} catch (Exception e2){
System.out.println("Unknown!");
}
}
public static void main(String[] args) {
// TODO code application logic here
doMatching();
}
And here is the result
Pattern: (\\w+\\b).*\\b\\1$
String: that sam-i-am
false
That will match some non-trivial number of word characters at the end of a word
(\\w+\\b)and ensure that they match at the end of the string as a complete word.