Reputation: 1894
I need a regex with the following requirements:
I have the following so far:
^[A-Za-z0-9][A-Za-z0-9/ ]{0,18}[A-Za-z0-9]$
I think it covers everything except consecutive slashes. Is there a way to meet this requirement in Java regex?
Upvotes: 2
Views: 894
Reputation: 627488
You can add that condition using a lookahead at the beginning:
^(?!.*//)[A-Za-z0-9][A-Za-z0-9/ ]{0,18}[A-Za-z0-9]$
^^^^^^^^
See the regex demo
The lookahead (?!.*//)
is negative due to (?!
and is failing the match once it finds any //
after any 0+ characters other than a newline (.*
).
You may use it without ^
and $
with String#matches
(see demo):
String input = "abc //abc";
if (!input.matches("(?!.*//)[A-Za-z0-9][A-Za-z0-9/ ]{0,18}[A-Za-z0-9]")) {
System.out.println("Not matching!");
}
as String#matches
requires a full string match, but I'd keep the anchors explicit for clarity.
Upvotes: 5