Kashiftufail
Kashiftufail

Reputation: 10885

Regex to match an optional '+' symbol followed by any number of digits

I want a regular expression to match a string that may or may not start with plus symbol and then contain any number of digits.

Those should be matched

+35423452354554
or
3423564564

Upvotes: 39

Views: 95281

Answers (4)

Gabber
Gabber

Reputation: 5452

This should work

\+?\d+

Matches an optional + at the beginning of the line and digits after it

EDIT:

As of OP's request of clarification: 3423kk55 is matched because so it is the first part (3423). To match a whole string only use this instead:

^\+?\d+$

Upvotes: 64

CaffGeek
CaffGeek

Reputation: 22054

Simple ^\+?\d+$

Start line, then 1 or 0 plus signs, followed by at least 1 digit, then end of lnie

Upvotes: 7

Jeff Bowman
Jeff Bowman

Reputation: 95614

It'll look something like this:

\+?\d+

The \+ means a literal plus sign, the ? means that the preceding group (the plus sign) can appear 0 or 1 times, \d indicates a digit character, and the final + requires that the preceding group (the digit) appears one or more times.

EDIT: When using regular expressions, bear in mind that there's a difference between find and matches (in Java at least, though most regex implementations have similar methods). find will find the substring somewhere in the owning string, and matches will try to match the entire string against the pattern, failing if there are extra characters before or after. Ensure you're using the right method, and remember that you can add a ^ to force the beginning of the line and a $ to force the end of the line (making the entire thing look like ^\+?\d+$.

Upvotes: 14

usta
usta

Reputation: 6869

A Perl regular expression for it could be: \+?\d+

Upvotes: 1

Related Questions