Help with regex in Java - sequence of numbers separated by commas

3

I'm breaking my head to put together a regular expression that validates the String:

/aluno/1/Teste dos Testes/1,2,3

String reg = "/aluno/[0-9]+/[^0-9]+/......."

I'm not able to validate the last field (the sequence of numbers) that:

  • Can be infinite numbers separated by commas.
  • You can not end up with anything other than a number.

That is, examples "1,2,3," , "1,2,3a" or "1,2,3,a" can not be accepted. Only valid sequences, such as "1,2,3,4,5,6" ...

Someone willing to help ??

    
asked by anonymous 22.04.2018 / 03:15

2 answers

3

You can use this regex:

(\/[\d,]+\d)$

Explanation:

\/[\d,] -> qualquer número precedido por vírgula até a barra
+         -> quantificador: une duas ou mais ocorrências
\d$      -> termina com um número
(...)     -> salva a ocorrência em um grupo

Examples:

aluno/1/Teste dos Testes/1,2,33,3,4 // retorna OK!
aluno/1/Teste dos Testes/1,2,33,3,4a // retorna Inválido! por causa do "a" no final
aluno/1/Teste dos Testes/1,2,33,3,a // retorna Inválido! por causa do "a" no final
aluno/1/Teste dos Testes/1,2,33a,3 // retorna Inválido! por causa do "a" no meio

Ideone Test

    
22.04.2018 / 03:58
1

Use the pattern /aluno/\d+?/\D+?/(\d+?,)*?\d+ .

  • (\d+?,)*? = > 0 or more numbers followed by a comma;
  • \d+ = > a last number that is not followed by a comma.

Example:

String t1 = "/aluno/1/Teste dos Testes/1";
String t2 = "/aluno/1/Teste dos Testes/1,23,456,789";
String t3 = "/aluno/1/Teste dos Testes/1,";
String t4 = "/aluno/1/Teste dos Testes/1,23,456,789,";
Pattern pattern = Pattern.compile("/aluno/\d+?/\D+?/(\d+?,)*?\d+");
System.out.println(pattern.matcher(t1).matches());  //true
System.out.println(pattern.matcher(t2).matches());  //true
System.out.println(pattern.matcher(t3).matches());  //false
System.out.println(pattern.matcher(t4).matches());  //false

See running here .

    
22.04.2018 / 04:03