[英]Length of some characters in regex
I have following regex:我有以下的正则表达式:
\+?[0-9\.,()\-\s]+$
which allows:这使得:
In addition to that I need to make sure that amount of numbers and plus symbol (if exists) has length between 9 and 15 (so I'm not counting any special characters apart from + symbol).此外,我需要确保数字的量与加号(如果存在)具有9和15之间的长度(所以我不从+符号计数任何特殊字符分开)。
And this last condition is what I'm having problem with.而这最后一个条件是我遇到的问题是什么。
valid inputs:有效输入:
invalid input:输入无效:
It is important to use regex if possible because it's used in javax.validation.constraints.Pattern annotation as:使用正则表达式,如果可能的话,是很重要的,因为它在javax.validation.constraints.Pattern标注所使用的:
@Pattern(regexp = REGEX)
private String number;
where my REGEX is what I'm looking for here.在我的正则表达式是什么,我这里寻找。
And if regex cannot be provided then it means that I need to rewrite my entity validation implementation.如果不能再提供正则表达式就意味着我需要重写我的实体验证实现。 So is it possible to add such condition to regex or do I need a function to validate such pattern?
所以是有可能这样的条件添加到正则表达式或者我需要一个函数来验证这种模式?
You may use您可以使用
^(?=(?:[^0-9+]*[0-9+]){9,15}[^0-9+]*$)\+?[0-9.,()\s-]+$
See the regex demo查看正则表达式演示
Details细节
^
- start of string ^
- 字符串的开始(?=(?:[^0-9+]*[0-9+]){9,15}[^0-9+]*$)
- a positive lookahead whose pattern must match for the regex to find a match: (?=(?:[^0-9+]*[0-9+]){9,15}[^0-9+]*$)
-一个正向前查找其模式必须为正则表达式找到一个匹配比赛:
(?:[^0-9+]*[0-9+]){9,15}
- 9 to 15 repetitions of (?:[^0-9+]*[0-9+]){9,15}
- 9至15重复[^0-9+]*
- any 0+ chars other than digits and +
symbol [^0-9+]*
-任何0+字符比其他数字和+
符号[0-9+]
- a digit or +
[0-9+]
-一个数字或+
[^0-9+]*
- 0+ chars other than digits and +
[^0-9+]*
- 0+比数字和其他字符+
$
- end of string $
- 字符串结尾\\+?
- an optional +
symbol -任选的
+
符号
[0-9.,()\\s-]+
- 1 or more digits, .
[0-9.,()\\s-]+
- 1位数以上, .
, ,
, (
, )
, whitespace and -
chars ,
, (
, )
, 空格和-
字符$
- end of string. $
- 字符串的结尾。 In Java, when used with matches()
, the ^
and $
anchors may be omitted:在Java中,当用于
matches()
该^
和$
锚可以被省略:
s.matches("(?=(?:[^0-9+]*[0-9+]){9,15}[^0-9+]*$)\\+?[0-9.,()\\s-]+")
Not using regex, you could simply loop and count the numbers and +
s:不使用正则表达式,您可以简单地循环并计算数字和
+
s:
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i)) || str.charAt(i) == '+') {
count++;
}
}
Since you're using Java, I wouldn't rely solely on a regex here:由于您使用的是Java,我不会只在这里依靠正则表达式:
String input = "+123,456.789";
int count = input.replaceAll("[^0-9+]", "").length();
if (input.matches("^\\+?[0-9.,()\\-\\s]+$") && count >= 9 && count <= 15) {
System.out.println("PASS");
}
else {
System.out.println("FAIL");
}
This approach allows us to just use straightaway your original regex.这种方法允许我们只使用通俗易懂你原来的正则表达式。 We handle the length requirements of numbers (and maybe plus) using Java string calls.
我们处理的数字(也许加)使用Java串的呼叫的长度要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.