简体   繁体   English

正则表达式匹配可选的“+”符号后跟任意数量的数字

[英]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).根据 OP 的澄清要求:3423kk55 匹配,因为它是第一部分(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.表示前一组(加号)可以出现0次或1次, \\d表示一个数字字符,最后的+要求前一组(数字)出现一次或多次。

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).编辑:使用正则表达式时,请记住查找匹配之间存在差异(至少在 Java 中,尽管大多数正则表达式实现具有类似的方法)。 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. find将在拥有的字符串中的某处找到子字符串,并且匹配将尝试将整个字符串与模式匹配,如果之前或之后有额外的字符,则失败。 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+$ .确保您使用了正确的方法,并记住您可以添加^以强制行首,并添加$以强制行尾(使整个内容看起来像^\\+?\\d+$

Simple ^\\+?\\d+$简单的^\\+?\\d+$

Start line, then 1 or 0 plus signs, followed by at least 1 digit, then end of lnie起始行,然后是 1 或 0 加号,后跟至少 1 位数字,最后是 lnie

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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