简体   繁体   中英

How to extract number only from string in flutter?

Lets say that I have a string:

a="23questions";
b="2questions3";

Now I need to parse 23 from both string. How do I extract that number or any number from a string value?

The following code can extract the number:

aStr = a.replaceAll(new RegExp(r'[^0-9]'),''); // '23'

You can parse it into integer using:

aInt = int.parse(aStr);
const text = "23questions";

Step 1: Find matches using regex:

final intInStr = RegExp(r'\d+');

Step 2: Do whatever you want with the result:

void main() {
  print(intInStr.allMatches(text).map((m) => m.group(0)));
}

The Answer in a single line with Null Safety enabled dart. or Flutter 2.0 will be:

int r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), '')) ?? defaultValue;
or
int? r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), ''));

but be warned that it will not work with the below string:

String problemString = 'I am a fraction 123.45';

And for many people below string will be a problem too, as it will parse 2030 and not 20 or 30 .

String moreProblem = '20 and 30 is friend';

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