如何改进我的正则表达式以检查数字是否在任何地方和任何数量包含唱歌?
How to improve my regex to check if number includes a sing in any place and in any amount?
我想检查 phone 数字是否仅包含数字,或者开头为“+”、一些“-”或空格。现在我检查是否只有数字和“+”。
我还希望允许将数字写为 123-456-678 或 123 445 6788。如何改进我的正则表达式,它可以在任何地方和任何数量中使用“-”或空格,但不是强制性的?
我的代码:
if (clientNumber.matches("^[+]?\d+")) {
System.out.println("OK");
} else {
System.out.println("ERROR");
}
以下正则表达式应该有效:^\+?\d+(( |-)\d+)*
- 以可选 +
开头的数字,后跟数字序列,然后是多个以单个
或开头的后缀-
.
在 Java 字符串中应该如下所示:number.matches("^\+?\d+(( |-)\d+)*")
使用
clientNumber.matches("\+?(?:[\s-]*\d)+")
不需要^
,matches()
要求整个字符串匹配正则表达式。
解释
--------------------------------------------------------------------------------
\+? '+' (optional (matching the most amount
possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (1 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
[\s-]* any character of: whitespace (\n, \r,
\t, \f, and " "), '-' (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
)+ end of grouping
或
clientNumber.matches("\+?(\d+[ -]*)+")
只允许 space 和破折号以及所有数字。
基本上,您可以通过多种方式执行此操作,并且可以在 regex101.com 网站上进行测试。
我想检查 phone 数字是否仅包含数字,或者开头为“+”、一些“-”或空格。现在我检查是否只有数字和“+”。
我还希望允许将数字写为 123-456-678 或 123 445 6788。如何改进我的正则表达式,它可以在任何地方和任何数量中使用“-”或空格,但不是强制性的?
我的代码:
if (clientNumber.matches("^[+]?\d+")) {
System.out.println("OK");
} else {
System.out.println("ERROR");
}
以下正则表达式应该有效:^\+?\d+(( |-)\d+)*
- 以可选 +
开头的数字,后跟数字序列,然后是多个以单个
或开头的后缀-
.
在 Java 字符串中应该如下所示:number.matches("^\+?\d+(( |-)\d+)*")
使用
clientNumber.matches("\+?(?:[\s-]*\d)+")
不需要^
,matches()
要求整个字符串匹配正则表达式。
解释
--------------------------------------------------------------------------------
\+? '+' (optional (matching the most amount
possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (1 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
[\s-]* any character of: whitespace (\n, \r,
\t, \f, and " "), '-' (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
)+ end of grouping
或
clientNumber.matches("\+?(\d+[ -]*)+")
只允许 space 和破折号以及所有数字。
基本上,您可以通过多种方式执行此操作,并且可以在 regex101.com 网站上进行测试。