TheGateKeeper
TheGateKeeper

Reputation: 4520

Telephone number regex with optional "+"

How would I go about building a regex that allows only digits, with no spaces, and an optional "+" at the beginning?

Upvotes: 0

Views: 2766

Answers (4)

James Laker
James Laker

Reputation: 41

I'm using the following:

(^\+?[0-9]{10,15})$

The + in the beginning is optional as indicated above, with added length restrictions (being minimum 10 digits & maximum 15)

Upvotes: 1

stema
stema

Reputation: 92976

try this

^\+?\d+$

^ anchors it to the start of the string, $ to the end

\+? is the optional +

\d is a digit and the following + is the quantifier that says at least one (digit).

A useful resource to learn regular expressions is the tutorial of regular-expressions.info

And Regexr is a very useful resource to test regular expressions, see this regex here online

Upvotes: 4

Dan
Dan

Reputation: 10786

You need to match a +,maybe, followed by digits. The + is a special character, so you need to escape it. To match a telephone number on its own (nothing else in the string) do ^\+?\d+$, to match it in a larger string omit the ^ and $ for just \+?\d+. You can obviously also change \d+ to \d{7} if you know how many digits there should be.

Upvotes: 1

Marian Galik
Marian Galik

Reputation: 876

This one should work: ^\+?\d+$

Upvotes: 1

Related Questions