0
\$\begingroup\$

In my country (South Africa) mobile numbers have 10 digits and always start with a "0" (e.g. 0821231231).

But they can also have the international dialing code ("+27") replacing the "0" (e.g. +27821231231).

I have this regex:

((\+27)|(^(?!\+)(0)))\d{9}

Is there any way that this can be improved upon?

\$\endgroup\$
2
  • \$\begingroup\$ I'm not sure if the negative lookahead (?!\+) is necessary. If the 0 is the very first char then there can't be ANY other char before. And because "any" includes the + I think it's unnecessary. \$\endgroup\$ Commented Mar 9, 2016 at 10:01
  • \$\begingroup\$ Since regex dialects vary wildly in syntax and features, regex questions should specify a specific language. \$\endgroup\$ Commented Dec 13, 2016 at 20:42

1 Answer 1

2
\$\begingroup\$

I guess it depends a bit on what kind of input text you have but if you wanna do exact match per line

^(\+27|0)\d{9}$

would work well. If you wanna be liberal what comes before and after then

.*(\+27|0)\d{9}.*

I agree with st88 that negative lookahead makes it confusing. Better to provide your expectation before and after the main pattern (like above)

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.