You can use a regular expression to extract the values of your String
:
([^,\:]+)\:([^\,]+)
This regular expression will look for any sequence of 1 or more characters that are not ,
nor :
( ([^,\:]+)
) followed by :
( \:
) that has any sequence of one or more characters that do not contain ,
( ([^\,]+)
). In%% we escaped the special characters of the regular expression with two bars ( Java
). So I came up with the following method that turns your \
into String
:
public static Map<String, String> separar(String texto) {
String regex = "([^,\:]+)\:([^\,]+)";
Map<String, String> resultado = new HashMap<>();
Pattern parte = Pattern.compile(regex);
Matcher matcher = parte.matcher(texto);
while (matcher.find()) {
String chave = matcher.group(1);
String valor = matcher.group(2);
resultado.put(chave.trim(), valor.trim());
}
return resultado;
}
You can test the method with your Map
as follows:
public static void main(String[] args) {
String texto = "Meu nome: Mariane Teixeira, Minha idade: 22";
Map<String, String> valores = separar(texto);
valores.forEach((chave, valor) -> System.out.println(chave + ": " + valor));
}
The value printed on String
would read as follows:
Meu nome: Mariane Teixeira
Minha idade: 22
Some comments:
-
Your console
is very much like the rating of a String
, although not% represents% valid%. So, consider using it.
-
In your example you used the code JSON
to generate the JSON
. The result would be "Meu nome: "+ "Mariane Teixeira" + ", Minha idade: "+ "22"
. If you want to put the values in quotation marks the assignment should be String
.