Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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 
like image 950
Kashiftufail Avatar asked Oct 02 '12 20:10

Kashiftufail


People also ask

Which regex matches one or more digits?

Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

What does \+ mean in regex?

Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol. Example: "^a" matches "a" at the start of the string. Example: "[^0-9]" matches any non digit. $ the dollar sign is the anchor for the end of the string.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


1 Answers

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+$ 
like image 176
Gabber Avatar answered Sep 17 '22 20:09

Gabber