简体   繁体   中英

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

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

Simple ^\\+?\\d+$

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

Perl 正则表达式可以是: \\+?\\d+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM