I need to validate a string in Java to fulfill the following requirements:
Would this regex be be a correct solution?
^(?!([^\\.]*+\\.){2,})[\\.a-z0-9_-]{5,32}$
You're pretty close, You can use this regex to block 2 periods in input:
^(?!([^.]*\\.){2})[.a-z0-9_-]{5,32}$
If you want to block 2 consecutive dots then use:
^(?!.*?\\.{2})[.a-z0-9_-]{5,32}$
I love regular expressions, but for reasons of readability and maintainability, I think they should be kept simple wherever possible, and that means using them for what they're good at, and using other features of your language/environment where appropriate.
In the comments you say this is for bean validation. You could validate your field with multiple simple annotations:
@Size(min=5,max=32)
@Pattern.List({
@Pattern(regexp = "^[a-z0-9-_.]*$",
message = "Valid characters are a-z, 0-9, -, _, ."),
@Pattern(regexp = "^((?!\.{2}).)*$",
message = "Must not contain a double period")
})
private String myField;
Also bear in mind that you can write custom constraints in Java.
... and of course in other contexts the same applies:
boolean isValid(String s) {
return s.length() >= 5 &&
s.length() <= 32 &&
s.matches("^[a-z0-9-_.]*$") &&
!s.contains("..")
}
This might work
# "^(?:[0-9a-z_-]|\\.(?!\\.)){5,32}$"
^
(?:
[0-9a-z_-]
| \.
(?! \. )
){5,32}
$
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.