Learning Bit by Bit – ELIZA

An ELIZA style chatbot using Regular Expressions

Though I struggled with RegEx I managed to put something together that is almost functional. I hope to grasp the potential power of using RegEx in different ways.

package class2.regexes;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Eliza2 {
 
public static void main(String[] args) {
System.out.println("What do you remember?");
//open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputText = "";
 
while (!inputText.equals("exit")){
try {
inputText = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read input");
System.exit(1);
}
String finalResult = "";
 
//re-assembly rule #1 * you * me -> * I * you
String regex1 = "you .+ me";
Pattern pattern1 = Pattern.compile(regex1);
Matcher matcher1 = pattern1.matcher(inputText);
 
//re-assembly rule #2
String regex2 = "[tT]he |[aA] |[aA]n .";
String replacement2 = "Hmm.. the ";
Pattern pattern2 = Pattern.compile(regex2);
Matcher matcher2 = pattern2.matcher(inputText);
 
//re-assembly rule #5
String regex5 = "\b[0-9] | (ago)?";
String replacement5 = " ";
Pattern pattern5 = Pattern.compile(regex5);
Matcher matcher5 = pattern5.matcher(inputText);
 
if (matcher1.find()){
String found = matcher1.group();
//System.out.println(found);
//replace "you" with "I"
Pattern you = Pattern.compile("you");
matcher1 = you.matcher(found);
String result1 = matcher1.replaceFirst("I");
 
//replace "me" with "you"
Pattern me = Pattern.compile("me");
matcher1 = me.matcher(result1);
String result2 = matcher1.replaceFirst("you");                
 
finalResult = "why do you think " + result2 + "?";
}
 
else if(matcher2.find()){
String result = matcher2.replaceFirst(replacement2);
finalResult = result + " sounds beatiful. How long ago was it?";
 
}
 
else if(matcher5.find()){
String result = matcher5.replaceFirst(replacement5);
finalResult = "Really? " + result + " isn't so long ago. What did it feel like?";
}
 
else{
finalResult = "hmm... I can't imagine it. What else do you remember?";
}
 
System.out.println(finalResult);
}
}
 
}
This entry was posted in Learning Bit by Bit, Spring 2011. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">