Use simple and easy to understand regular expressions in your code

I used regular expressions a few times in my test automation code and each time they were not easy to understand by other people.

It is possible to make them readable as explained in Martin Fowler's article on REGEX.

For this text (score 400 for 2 nights at Minas Tirith Airport), instead of using 

const string pattern = 


private String composePattern(params String[] arg) {
      return "^" + String.Join(@"\s+", arg);
const string numberOfPoints = @"(\d+)";
const string numberOfNights = @"(\d+)";
const string hotelName          = @"(.*)";

const string pattern =  composePattern("score", numberOfPoints, 
      "for", numberOfNights, "nights?", "at", hotelName);

Instead of having a long and complicated expression, have a few simple, short expressions that are joined together into a long regular expression.

Share this