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 =
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 =
@"^score\s+(\d+)\s+for\s+(\d+)\s+nights?\s+at\s+(.*)";
use
private String composePattern(params String[] arg) {
return "^" + String.Join(@"\s+", arg);
}
andconst 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.
0 Response to "Use simple and easy to understand regular expressions in your code"
Post a Comment