Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Presentation error when there are keywords in comments.


So this is how you define a simple boolean expression involving a regular expression. But let's get a little bit more tricky. Let's define a method that tests a regular expression. So for example, let's write some code to match Pete Wisniewski's last name:

Code Block

def checkSpelling(spellingAttempt, spellingRegularExpression)
	        if (spellingAttempt ==~ spellingRegularExpression)
                println("Congratulations, you spelled it correctly.")
	        } else {
		                println("Sorry, try again.")

theRegularExpression = /Wisniewski/
checkSpelling("Wisniewski", theRegularExpression)
checkSpelling("Wisnewski", theRegularExpression)


Code Block
// evaluates to true, and will for anything ending in a question mark (that doesn't have a question mark in it)
"How tall is Angelina Jolie?" ==~ /[^\?]+\?/

This is your first really ugly regular expression. (The frequent use of these in PERL is one of the reasons it is considered a "write only" language). By the way, google knows how tall she is. The only way to understand expressions like this is to pick it apart:




? $

begin expression

any character other than '?'

more than one of those

a question mark

end expression

So the use of the ** the \ in front of the * ? makes it refer to an actual question mark.