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

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+$

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+$.

Tags:

Regex