/* http://pt.stackoverflow.com/q/177044/53463 */
import java.util.regex.Matcher ;
import java.util.regex.Pattern ;
class Ideone
{
{
final String regex
= "\\ G" // Início do texto ou fim do casamento anterior + "[^\\ [']*" // Texto sem colchetes nem aspas simples
+ "(?:'[^']*'[^\\ ['*]*)*" // Opcional: Texto em aspas + texto sem "[" nem "'"
+ "(\\ [" // Grupo 1: Colchete de abertura
+ "[^]']*" // + texto sem "]" nem "'"
+ "(?:'[^']*'[^]']*)*" // + texto em aspas + texto sem "]" nem "'"
+ "\\ ])" ; // + colchete de fechamento
final Pattern pat = Pattern.compile ( regex) ;
Matcher mat;
"1 + [aa]" ,
"[bb] + 2" ,
"'a' + [cc]" ,
"['ola' + 'mundo']" ,
"'[a' + 'b]'" ,
"'[' + ']'" ,
"[]" ,
"'Ola [world] legal'" ,
"Oi ['[aa]'] ola"
} ;
//Loop cada string na entrada
for ( String stringlToVerify
: entrada
) { mat = pat.matcher ( stringlToVerify) ;
System .
out .
println ( "\n Entrada: " + stringlToVerify
) ;
if ( mat.find ( ) )
do { // Loop cada texto entre colchetes casado
System .
out .
println ( "Captura: " + mat.
group ( 1 ) ) ; } while ( mat.find ( ) ) ;
else
System .
out .
println ( "Não há colchetes fora das aspas" ) ; }
}
}
LyogaHR0cDovL3B0LnN0YWNrb3ZlcmZsb3cuY29tL3EvMTc3MDQ0LzUzNDYzICovCgppbXBvcnQgamF2YS51dGlsLnJlZ2V4Lk1hdGNoZXI7CmltcG9ydCBqYXZhLnV0aWwucmVnZXguUGF0dGVybjsKCmNsYXNzIElkZW9uZQp7CglwdWJsaWMgc3RhdGljIHZvaWQgbWFpbiAoU3RyaW5nW10gYXJncykgdGhyb3dzIGphdmEubGFuZy5FeGNlcHRpb24KCXsKCQlmaW5hbCBTdHJpbmcgcmVnZXggPSAiXFxHIiAgICAgICAgICAgICAgICAgICAgLy8gSW7DrWNpbyBkbyB0ZXh0byBvdSBmaW0gZG8gY2FzYW1lbnRvIGFudGVyaW9yCgkJICAgICAgICAgICAgICAgICAgICsgIlteXFxbJ10qIiAgICAgICAgICAgICAgIC8vIFRleHRvIHNlbSBjb2xjaGV0ZXMgbmVtIGFzcGFzIHNpbXBsZXMKCQkgICAgICAgICAgICAgICAgICAgKyAiKD86J1teJ10qJ1teXFxbJypdKikqIiAgLy8gT3BjaW9uYWw6IFRleHRvIGVtIGFzcGFzICsgdGV4dG8gc2VtICJbIiBuZW0gIiciCgkJICAgICAgICAgICAgICAgICAgICsgIihcXFsiICAgICAgICAgICAgICAgICAgIC8vIEdydXBvIDE6IENvbGNoZXRlIGRlIGFiZXJ0dXJhCgkJICAgICAgICAgICAgICAgICAgICsgICAgICJbXl0nXSoiICAgICAgICAgICAgIC8vICAgICAgICArIHRleHRvIHNlbSAiXSIgbmVtICInIgoJCSAgICAgICAgICAgICAgICAgICArICAgICAiKD86J1teJ10qJ1teXSddKikqIiAvLyAgICAgICAgKyB0ZXh0byBlbSBhc3BhcyArIHRleHRvIHNlbSAiXSIgbmVtICInIgoJCSAgICAgICAgICAgICAgICAgICArICJcXF0pIjsgICAgICAgICAgICAgICAgICAvLyAgICAgICAgKyBjb2xjaGV0ZSBkZSBmZWNoYW1lbnRvCgkJZmluYWwgUGF0dGVybiBwYXQgPSBQYXR0ZXJuLmNvbXBpbGUocmVnZXgpOwoJCU1hdGNoZXIgbWF0OwoJCQoJCWZpbmFsIFN0cmluZ1tdIGVudHJhZGEgPSB7CgkJICAgICIxICsgW2FhXSIsCgkJICAgICJbYmJdICsgMiIsCgkJICAgICInYScgKyBbY2NdIiwKCQkgICAgIlsnb2xhJyArICdtdW5kbyddIiwKCQkgICAgIidbYScgKyAnYl0nIiwKCQkgICAgIidbJyArICddJyIsCgkJICAgICJbXSIsCgkJICAgICInT2xhIFt3b3JsZF0gbGVnYWwnIiwKCQkgICAgIk9pIFsnW2FhXSddIG9sYSIKCQl9OwoJCQoJCS8vTG9vcCBjYWRhIHN0cmluZyBuYSBlbnRyYWRhCgkJZm9yIChTdHJpbmcgc3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