Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Dart: How to extract a number from a string using RegEx

I want to extract a number (integer, decimal or 12:30 formats) from a string. I have used the following RegEx but to no avail:

final RegExp numberExp = new RegExp(
      "[a-zA-Z ]*\\d+.*",
      caseSensitive: false,
      multiLine: false
    );
final RegExp numberExp = new RegExp(
      "/[+-]?\d+(?:\.\d+)?/g",
      caseSensitive: false,
      multiLine: false
    );
String result = value.trim();
result = numberExp.stringMatch (result);
result = result.replaceAll("[^0-9]", "");
result = result.replaceAll("[^a-zA-Z]", "");

So far, nothing works perfectly.

Any help appreciated.

like image 318
LiveRock Avatar asked Dec 04 '18 17:12

LiveRock


People also ask

How do you get a number from a string in RegEx?

To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string. [0-9]+ represents continuous digit sequences of any length.

How do you get only numbers from string in darts?

A string can be cast to an integer using the int. parse() method in Dart. The method takes a string as an argument and converts it into an integer.

How do you get the int of a string in flutter?

Parse a String into an int in Dart/Flutter try { var n = int. parse('n42'); print(n); } on FormatException { print('Format error! '); } // Format error! int class parse() method also gives us a way to handle FormatException case with onError parameter.


2 Answers

const text = '''
Lorem Ipsum is simply dummy text of the 123.456 printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an 12:30 unknown printer took a galley of type and scrambled it to make a
23.4567
type specimen book. It has 445566 survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
''';

final intRegex = RegExp(r'\s+(\d+)\s+', multiLine: true);
final doubleRegex = RegExp(r'\s+(\d+\.\d+)\s+', multiLine: true);
final timeRegex = RegExp(r'\s+(\d{1,2}:\d{2})\s+', multiLine: true);
void main() {
  print(intRegex.allMatches(text).map((m) => m.group(0)));
  print(doubleRegex.allMatches(text).map((m) => m.group(0)));
  print(timeRegex.allMatches(text).map((m) => m.group(0)));
}
like image 118
Günter Zöchbauer Avatar answered Nov 16 '22 03:11

Günter Zöchbauer


For one-line strings you can simply use:

final intValue = int.parse(stringValue.replaceAll(RegExp('[^0-9]'), ''));
like image 29
Andrey Gordeev Avatar answered Nov 16 '22 03:11

Andrey Gordeev