I am trying to match a string in Java with String.matches().
Accepted values are
but
should not match.
So /
may be in middle or at the end of the string but not at the beginning and it should appear only once.
This is the closest regexp I have managed to do:
myString.matches("^[A-Za-z0-9]+/?[A-Za-z0-9]+/?$");
but the problem is that / may appear multiple times. So how can I improve the regex to allow / only once?
The problem with your regex is that you allow /
at least 2 times with /?
.
You need to only allow the /
once.
^[A-Za-z0-9]+/?[A-Za-z0-9]*$
Also, matches
requires a full string match, no need to use ^
and $
anchors in this regex if you only plan to use it with matches
.
See IDEONE demo
System.out.println("ABC321".matches("[A-Za-z0-9]+/?[A-Za-z0-9]*"));
System.out.println("ABC321/OTHER888".matches("[A-Za-z0-9]+/?[A-Za-z0-9]*"));
System.out.println("ABC321/".matches("[A-Za-z0-9]+/?[A-Za-z0-9]*"));
System.out.println("/ABC321".matches("[A-Za-z0-9]+/?[A-Za-z0-9]*"));
System.out.println("ABC321/OTHER888/".matches("[A-Za-z0-9]+/?[A-Za-z0-9]*"));
Output:
true
true
true
false
false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With