Home > Enterprise >  How to extract specific string from whole string?
How to extract specific string from whole string?

Time:07-29

I have following strings :

String? hello = "(1.2,1.5 | 5)"
String? hi = "(2.3,3.2 | 9)"

Now I want to get

var newhello1 = 1.2,1.5
var newhello2 = 5

and

var newhi1 = 2.3,3.2
var newhi2 = 9

How to extract those text from that entire strings?

CodePudding user response:

You can use the indexOf function combined with the substring to get the substrings as follows

var newhello1 = hello.substring(hello.indexOf('(')   1, hello.indexOf('|')).trim(); //Use Trim() to get rid of any extra spaces
var newhello2 = hello.substring(hello.indexOf('|')   1,hello.indexOf(')')).trim();
print(newhello1); //1.2,1.5
print(newhello2); //5

CodePudding user response:

List<String> myformatter(String? data) {
  if (data == null) return [];
  List<String> ls = data.split("|");

  for (int i = 0; i < ls.length; i  ) {
    ls[i] = ls[i].replaceAll("(", "").replaceAll(")", "").trim();
  }
  return ls;
}

main() {
  String? hello = "(1.2,1.5 | 5)";
  String? hi = "(2.3,3.2 | 9)";

  final helloX = myformatter(hello);

  print(helloX[0]); //1.2,1.5 
  print(helloX[1]); //5

  final hiX = myformatter(hi);
  print(hiX[0]); //2.3,3.2 
  print(hiX[1]); //9
}

  • Related