Tuesday, 19 November 2013

Regular Expressions

Regular Expressions

Assignment 2 was about a simplified version of Regular Expressions. Being curious, I studied a bit more on regexes. Regexes are mainly used in pattern matching with strings, or string matching ie. checking to see if a string matches the format of a valid email address.

Here, I want to provide a list of the most common meta-characters that are used in regexes:
  • ".":  Despite what you might think after having completed assignment 2, the dot does not represent the joining of two expressions. It means any character except a new line ( a literal dot would be [.]). If you want to show the joining of two expressions, you just put them one after the other without anything in between.
  • "( )": Groups a series of pattern elements to a single element.
  • "+": Matches the element or pattern preceding it one or more times.
  • "?": Matches the element or pattern preceding it zero or one times.
  • "*": Matches the preceding pattern or element zero or more times.
  • "{M,N}": Matches the preceding pattern or element at least M times and at most N times.
  • "[...]": A set of possible character matches.
  • "|": Alternate possibilities.
  • "\b": I'm not sure what this one means. This is what Wikipedia is telling me, "Matches a zero-width boundary between a word-class character (see next) and either a non-word class character or an edge."
  • "\w": Matches an alphanumeric character.
  • "\W": Matches a non-alphanumeric character.
  • "\s": Matches a whitespace character.
  • "\S": Matches anything but a whitespace.
  • "\d": Matches a digit.
  • "\D": Matches a non-digit.
  • "^": Matches the beginning of a line or string.
  • "$": Matches the end of a line or string.
  • "\A": Matches the beginning of a string.
  • "\z": Matches the end of a string.
  • "[^...]": Matches every character except the ones inside the brackets.
So, no you can understand what the following regex means:
  • \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
Lets go through this step by step:
  1. Start of regex
  2. Any alphanumeric character or one of the following: ., _, %, +, -
  3. 2 repeated 1 or more times
  4. The "@" character
  5. Any alphanumeric character or the "-" character
  6. The "." character
  7. An alphabet
  8. Step 7 repeated from 2 to 4 times
  9. End of regex
As you might have guessed, this regex checks if a string has the format of a valid email address. WOOHOO! WE ROCK! :D

No comments:

Post a Comment