How to combine a character in the middle or at the end of a line, but only once

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

Accepted Values

  • ABC321,
  • ABC321 / OTHER888
  • or ABC321 /

but

  • / ABC321
  • or ABC321 / OTHER888 /

should not match.

So, / can be in the middle or at the end of a line, but not at the beginning, and it should only appear once.

This is the closest regex I managed to do:

 myString.matches("^[A-Za-z0-9]+/?[A-Za-z0-9]+/?$"); 

but the problem is that / may appear several times. So, how can I improve the regex to allow / only once?

+6
source share
3 answers

The problem with your regex is that you allow / at least 2 times with /? .

You need to allow only / once.

 ^[A-Za-z0-9]+/?[A-Za-z0-9]*$ 

In addition, matches requires complete string matching, no ^ and $ bindings are needed in this regular expression if you plan to use it only with matches .

Watch the 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 
+6
source

This regex will work

 ^[A-Za-z0-9]+\/{0,1}[A-Za-z0-9]*$ 

{0,1} provides an appearance of "/" at least 0 times and a maximum of 1 time.

0
source

I would use a negative look to claim only 1 slash, and the rest is simple:

 if (str.matches("(?!.*/.*/)\\w[\\w/]+")) 

See (equivalent) live demo .

0
source

Source: https://habr.com/ru/post/989000/


All Articles