Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a character in middle or at the end of string but only once

Tags:

java

regex

I am trying to match a string in Java with String.matches().

Accepted values are

  • ABC321,
  • ABC321/OTHER888
  • or ABC321/

but

  • /ABC321
  • or ABC321/OTHER888/

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?

like image 786
Devnullable Avatar asked Jun 12 '15 11:06

Devnullable


1 Answers

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
like image 177
Wiktor Stribiżew Avatar answered Oct 30 '22 03:10

Wiktor Stribiżew