Home > Back-end >  Regex split java
Regex split java

Time:10-18

Good fellows, could you help me find a regex with split to separate the attributes of a string (txt file), the string is the following line:

{'title': 'The signal', 'description': 'Una crisis nerviosa. Un ataque de pánico en pleno sermón, 'img': '9b9f6e903588a16bf90eb86ff7b079ba.jpg', 'Format': 'physic book', 'Author': 'Young, wm. paul - jersak, bradley', 'Editorial': 'Diana', 'Year': '2021', 'Idiom': 'Español', 'Isbn': '9789584293817', 'Isbn13': '9789584293817'}{'titulo': 'Quemar el Miedo', 'descripcion': 'Este es el manifiesto escrito por el Colectivo LASTESIS. , 'img': 'f56123687ddc0167a0f4186612293435.jpg', 'Formato': 'Libro físico', 'Autor': '', 'Año': '2021', 'Idioma': 'Español', 'Isbn': '9789584293626', 'Isbn13': '9789584293626'}

I need to get the values ​​of each element to be able to rebuild the object

public static boolean cargarlibros(){    
  File f = new File(FILENAME);
  FileReader reader;
  try {
    reader = new FileReader(f);
    BufferedReader buffr = new BufferedReader(reader);
    String registro; 
    while((registro = buffr.readLine()) != null){
      String[] datos = registro.split("\\{\\}");
      System.out.println(Arrays.toString(datos));                              
    }
    buffr.close();
    reader.close();
  } catch (IOException ex) {
    return false;
  }        
  return true;
}

CodePudding user response:

You could try to add and change quotes in order to convert your data to JSON, but that may be not trivial especially if the string contains apostrophes, and I think parsing it as is is easier. Your split attempt didn't work because the pattern "\\{\\}" would only split at {}, which isn't there. You could replace

      String[] datos = registro.split("\\{\\}");

with

      String[] datos = registro.replaceFirst("^\\{", "").split("}\\{|}$");
      for (var dato: datos)
      {
        String[] elems = dato.replaceFirst("^'", "").split("'?[:,] '|'$");
        Map<String, String> book = new LinkedHashMap<String, String>();
        for (int i = 0; i < elems.length; ) book.put(elems[i  ], elems[i  ]);
        …
      }

As you didn't say into what data structure you want to get the values ​​of each element, I chose a Map.

  • Related