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.
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.
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)
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.
Example is: string pattern = @"(Band) (? <Band>[A-Za-z ]+) (? <City>@[A-Za-z ]+) (?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With