3
I need to capture strings between brackets within a string. I found a solution that doesn’t solve my problem completely: \\[(.*?)\\]
Use like this:
Matcher mat = Pattern.compile("\\[(.*?)\\]").matcher(stringlToVerify);
if(mat.find()) {
// Faz o que quero
}
That way, if I run the regex with: 'ol[a' + 'm]undo'
He’s gonna get: [a' + 'm]
But in this case it is not to take, because the two strings are being concatenated, so it makes no sense.
Example of what I need:
Entrada Captura
1 + [aa] [aa]
[bb] + 2 [bb]
'a' + [cc] [cc]
['ola' + 'mundo'] ['ola' + 'mundo']
'[a' + 'b]'
'[' + ']'
[] [] (ou nada, também serve)
'Ola [world] legal'
Oi ['[aa]'] ola '[aa]'
In the latter case, if it is not possible to do it simply, it is no problem. I made a method that removes all strings between single quotes.
Hello Eduardo, say, a valid input would be a string that must be in quotes and in brackets? For example: 'hello [dear] world', where the word "wanted" would be captured? If possible try to further detail your requirements. Very complex regular expressions can disturb rather than help.
– Renato Colaço
@Eduardo And what to capture with this text:
['aa']
?– Mariano
@Renatocolace, if the string 'hello [wanted] world' was tested, the return should be empty. I updated the list of inputs and outputs in my question by adding this scenario. Thank you.
– Eduardo H. M. Garcia
@Mariano, if the string is input ['aa'] the return should be 'aa' or ['aa'], whatever, the important thing is to capture what is in parentheses.
– Eduardo H. M. Garcia
@Eduardoh.M.Garcia There may be quotes with escapes? (
'a \'b\' [c] d' [e]
)– Mariano
The latter case is inconsistent. It should be
['[aa]']
– Mariano