Regular expression… Postcode (UK)
You can do so much with regular expressions that it becomes one of the most attractive programming tools. I guess you can avoid them (I am not sure how) and extract your information from a text without them, but it will be a painful procedure.
Well this article is not about explaining them, is more like… hmm… Beat it and I will reconsider:
The most common examples where are I use them are:
- Extracting information from a long piece of text.
- Validating an input field.
The first one is fairly straight forward, you have a text and you want find something in particular, such as matching a word, a value and so on…
The other one, is the main reason of the article.
You often have a textfield for the user to enter a value. How do you validate the input? You cannot iterate through the characters and it would be very complex. Consider an example where a textfield accepts only postcodes (it is like the MOST sensible paradigm I can give)
Here is the format of the british postcodes:
A9 9AA, A99 9AA, AA9 9AA, AA99 9AA, A9A 9AA, AA9A 9AA
How will you do that? If you can do it without regular expressions I would be amazed… I have not checked the processing time, but I am happy to do so if you think you can do it faster.
- Yeah clearly the first one needs to be a letter
- We also know that it ends with a number followed by two letters. Cool. (9AA)
What about the rest:
- Then it could be a letter or a number (AA9 9AA , A9 9AA)
- Then it could be a space, or a letter or a number (A9_9AA, A9A 9AA , AA99 9AA)
- Then it could be a space, or a letter or a number (AA9_9AA , AA9A 9AA , AA99 9AA)
- Then it could be a space (AA9A_9AA)
Think about it so many combinations.
The following expression does it for you…
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^([A-Z])([A-Z]|[0-9])?([0-9]|[A-Z])?([0-9]|[A-Z])([\\s]*)[0-9][A-Z][A-Z]$" options:NSRegularExpressionSearch | NSRegularExpressionCaseInsensitive error:nil]; // search for matches NSUInteger numberOfMatches = [regex numberOfMatchesInString:[textField text] options:0 range:NSMakeRange(0, [[textField text] length])]; // if it's a postcode enable the button // else disable it if (numberOfMatches>0) { // found a match do something // maybe enable the done button } else { // did not found a match do something else // maybe disable the done button }
So much power... formal definitions, seriously you cannot beat that…