Java regex help - comma-separated sequence of numbers

Asked

Viewed 677 times

3

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

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

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

I’m having trouble validating last field (the sequence of numbers) which:

  • It can be infinitely numbers separated by a comma.
  • Can’t end up in anything but a number.

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

Someone willing to help??

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

Testing at Ideone

  • It worked. Thank you very much!

1

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

  • (\\d+?,)*? => 0 or more consecutive decimal;
  • \\d+ => a last number which 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 spinning here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.