Skip to content

CommonRegularExpressions

Tim Bourguignon edited this page Feb 11, 2014 · 10 revisions

Searching for validation of the SimpleExpression framework, I stumbled upon the following page which describes some examples of Regular Expressions one should know. I don't agree with the idea behind some of them (limiting the number of characters of a password for instance) but since it's not the point of this exercise, here are the corresponding SimpleExpressions:

Matching a username: /^[a-z0-9_-]{3,16}$/

se.StartsWith
  .EitherOf
    .Alphanumerics.EitherIn("_-")
  .Count.AtLeast(3).AtMost(16)
  .Then
  .EndOfLine

Matching a password: /^[a-z0-9_-]{6,18}$/

se.StartsWith
  .EitherOf
    .Alphanumerics.EitherIn("_-")
  .Count.AtLeast(6).AtMost(18)
  .Then
  .EndOfLine

Matching a Hex Value: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/

se.StartsWith
  .Maybe.One("#")
  .Either
    .EitherOf.Letters.InRange("a-f").Numbers.Exactly(6)
  .Or
    .EitherOf.Letters.InRange("a-f").Exactly(3)
  .Then
  .EndOfLine

Matching a slug: /^[a-z0-9-]+$/

se.StartsWith
  .EitherOf
    .Alphanumerics.Text("-")
  .Then
  .EndOfLine

Matching an email: /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/

se.StartsWith
  .EitherOf
    .Alphanumerics.EitherIn("_.-")
  .Then.One("@").Then
  .EitherOf
    .Alphanumerics.EitherIn("_.-")
  .Then.One(".").Then
  .EitherOf
    .Letters.Text(".")
  .Count.AtLeast(2).AtMost(6)
  .Then.EndOfLine

Matching an URL: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

se.StartsWith
  .Maybe
    .Text("http").Maybe("s").Text("://")
  .Then
  .EitherOf
    .Alphanumerics.EitherIn("/_ .-")
  .Then
  .EitherOf
    .Letters.Text(".").Count.AtLeast(2).AtMost(6)
  .Then
  .Maybe("/")
  .Then
  .EndOfLine

Matching an IP Address:

se.StartsWith
  .Numbers.InRange("1-255)
  .Then
  .Repeat
    .One(".")
    .Numbers.InRange("0-255")
  .Exactly(2)
  .Then
  .One(".")
  .Then
  .Numbers.InRange("0-255")

Matching an HTML Tag: /^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/

se.StartsWith.One("<")
  .Group
    .Letters.AtLeast(1)
  .Together
  .Then
  .AnythingBut(">").AtLeast(1)
  .Then
  .Either
    .Text("</")
    .Then
    .Group
      .Letters.AtLeast(1)
    .Together
  .Or
    .One(" /")
  .Then
  .One(">")
  .Then.EndOfLine
Clone this wiki locally