How do I remove a part of a string?

-2

I have text saved in a string and need to copy a portion of this text to the find a certain word in it.

Eg: I need to remove my name and age from this text, I know they always come after: and in quotation marks.

String texto = "Meu nome: "+ "Mariane Teixeira" + ", Minha idade: "+ "22";

//resposta
String nome = "Mariane Teixeira"
String idade = "22"

I can use FLAG as: or "" or the word "name" and "age" and copy what comes after them, but I do not know how to do this using java code.

    
asked by anonymous 08.09.2017 / 21:46

2 answers

2

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 .

11.09.2017 / 21:35
1

A very lazy way to solve:

String text = "Meu nome: \"Mariane Teixeira\", Minha idade: \"22\"";
String [] textArray = text.split("\"");

System.out.println(Arrays.toString(textArray));

System.out.println("Meu nome: " + textArray[1]);
System.out.println("Minha idade: " + textArray[3]);
    
08.09.2017 / 23:39