Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get all substrings matching a RegExp in Dart

Tags:

regex

dart

I want to get a list of substrings matching a RegExp in a string. What is the best way to do this?

RegExp object from dart:core has Iterable<Match> allMatches(String input, [int start=0]) method. This is kind of what I need, but I want to get Iterable of Strings, not matches.

There is also method String stringMatch(String input), which returns a String, but only a first match.

So I wrote myslef this function using map:

Iterable<String> _allStringMatches(String text, RegExp regExp) {
  Iterable<Match> matches = regExp.allMatches(text);
  List<Match> listOfMatches = matches.toList();

  // TODO: there must be a better way to get list of Strings out of list of Matches
  Iterable<String> listOfStringMatches = listOfMatches.map((Match m) {
    return m.input.substring(m.start, m.end);
  });

  return listOfStringMatches;
}

but it seems to me that it is pretty basic functionality and I can't believe it is not in anywhere in the API. I guess there must be a better way to do such a basic task.

like image 643
Luboš Turek Avatar asked Dec 18 '14 11:12

Luboš Turek


People also ask

How do you check if a string matches a regex in Dart?

RegExpMatch firstMatch(String input) : This returns the first regex match on the input string. Method returns null if no match is found. bool hasMatch(String input) : This function returns a bool that determines whether or not an input string has at least one match.

What is full match in regex?

The fullmatch() function returns a Match object if the whole string matches the search pattern of a regular expression, or None otherwise. The syntax of the fullmatch() function is as follows: re.fullmatch(pattern, string, flags=0)

How do you get a substring in darts?

To find the substring of a string in Dart, call substring() method on the String and pass the starting position and ending position of the substring in this string, as arguments.

How do you match a specific sentence in regex?

Example is: string pattern = @"(Band) (? <Band>[A-Za-z ]+) (? <City>@[A-Za-z ]+) (?


1 Answers

If your regexp contains only one group (like new RegExp(r'(\S+)')) you can rewrite your function to:

Iterable<String> _allStringMatches(String text, RegExp regExp) => 
    regExp.allMatches(text).map((m) => m.group(0));
like image 59
Alexandre Ardhuin Avatar answered Nov 15 '22 13:11

Alexandre Ardhuin