0
\$\begingroup\$

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]\\.).*")
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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.*"
\$\endgroup\$
3
  • \$\begingroup\$ 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 :) \$\endgroup\$ Sep 30, 2015 at 20:56
  • \$\begingroup\$ My last iteration: ".*\\b[nN](\\.?)-?[bB]\\1(\\W.*|$)" Does exactly what I want (e.g., it will match "Funny st., Citiville, N.B., Canada"). \$\endgroup\$ Oct 1, 2015 at 13:06
  • \$\begingroup\$ Fantastic! Glad i was able to help \$\endgroup\$
    – Shaun H
    Oct 1, 2015 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.