# Check the address String for presence of a New Brunswick abbreviation

I need to check if there are any abbreviation of New Brunswick province in the address. Acceptable abbreviations are: "NB", "N.B.", "N-B", "N.-B." and any combination of upper-lower cases. It shouldn't be a part of another word, hence the "\b" separators.

The hardest part was checking the dot in the end, because of the greediness of the "\b". So, the part "\.\b" doesn't work, because the dot is within the word boundary, so it is being "attached" to "\b".

Is there a way to avoid such behaviour and are there other suggestions to improve on the regex?

return addressLine?.matches(".*\\b([nN]-?[bB]\\b|[nN]\\.-?[bB]\\.).*")


Depending on your requirements for word breaks the following should do nicely:

/.*\b[nN](\.)?-?[bB]\1?\s.*/


Caveat only checks for a space after N?B?

Or in as in your question language(ruby?):

return addressLine?.matches(".*\\b[nN](\\.)?-?[bB]\\1?\\s.*"

• Nice! I didn't think about the \1 approach. As for the \s, I don't think it would do, I'd prefer without it at all. I.e., I want to detect N.B.Canada as New Brunswick, but if it detects N.-B as New Brunswick too, I don't mind :) Sep 30, 2015 at 20:56
• My last iteration: ".*\\b[nN](\\.?)-?[bB]\\1(\\W.*|\$)" Does exactly what I want (e.g., it will match "Funny st., Citiville, N.B., Canada"). Oct 1, 2015 at 13:06
• Fantastic! Glad i was able to help Oct 1, 2015 at 18:31