简体   繁体   中英

How do I extract only numbers from a string in Dart?

I was trying to sort the string using -

for (var t in creditcards) {
  print(t['firstyear'].toString().replaceAll('/[^0-9]/', ''));
}

Its output -

Rs.500
Rs.1000
Rs.500
Rs.0
Rs.499
Rs.499 + applicable taxes
Rs.500
Rs.500
Rs.495 + taxes
Rs.0

I want to remove ' + applicable taxes' from this and parse it as integer.

Without an example of how your String is it's hard to say what or how can we avoid certain patterns. This works as long as your Strings is always in the format Letters.numbers (any amount of letters, then a dot, then any amount of numbers)

String x = 'Rs.499 + applicable taxes';
String y = ' asdhui Euro.3243 + applicable taxes';
final RegExp firstRegExp = RegExp('[a-zA-Z]+(\.[0-9]+)'); 
final RegExp example = RegExp(r'\w+(\.\d+)'); //this is basically the same that the one above, but also check for numbers before the dot

//consider static final RegExp to avoid creating a new instance every time a value is checked

print(firstRegExp.stringMatch(x));
print(example.stringMatch(x));
print(example.stringMatch(y));

for (var t in creditcards) {
  print(example.stringMatch(t['firstyear'].toString()));
}

RegExp check for the pattern [a-zA-Z] which means any letter, + match the previous one or more times (the prvious means it will match a one or more letters, but not space, tabs or any special character), (.[0-9]+) the. checks for a dot (\ is used because. is a special character in regExp and you want to search explicitly for the dot), [0-9]+ checks for one or more numbers after the dot

RegExp is used to check for patterns, check more about it in regExp Dart and some examples about special characters in RegExp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM