Search code examples
javareplaceall

Java replaceAll for separated comma String with regex


I have this String:

String a = [MercadosArmados.GpoMerc-CTN3].[Mercado Marketing SNC].[Mk Alprazolam], [MercadosArmados.GpoMerc-CTN3].[Mercado Marketing SNC].[Mk Amantadina]

I need to extract just the 3rd [value] of every comma separated block. For example, I need to print: Mk Alprazolam, Mk Amantadina

I'll put it in a textfield expression of a JasperReport so I need to achieve it in one line. Example:

a.substring(0, a.indexOf(",")).substring(a.substring(0, a.indexOf(",")).lastIndexOf("[")).replace("[", "").replaceAll("]", "")

this returns: Mk Alprazolam... but I need it for every comma separated block (it could be 1+).

I've tried some regular expressions with .replaceAll but can't achieve it.

Any help would be appreciated.

Thanks


Solution

  • Pure replaceAll() solution:

    s = s.replaceAll("\\[[^\\]]*\\]\\.|[\\[\\]]", "");
    

    See regex101 for demo.

    Explanation

    Initial text:

    [MercadosArmados.GpoMerc-CTN3].[Mercado Marketing SNC].[Mk Alprazolam], [MercadosArmados.GpoMerc-CTN3].[Mercado Marketing SNC].[Mk Amantadina]

    First it matches [xxx]. and replaces them with nothing. That leaves:

    [Mk Alprazolam], [Mk Amantadina]

    It then also matches [ and ] and replaces them with nothing. Result:

    Mk Alprazolam, Mk Amantadina