dart-lang / dart-lang/language
RegExp could express its capture groups as a type argument
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
With the introduction of records and pattern matching it is interesting to consider how `RegExp` API could be extended to make use of these feature, consider for example the following code:
```dart
final re = RegExp(r"(?\d+).(?\d+).(?\d+)");
final m = re.firstMatch(version)!;
final major = m.namedGroup('major')!;
final minor = m.namedGroup('minor')!;
final patch = m.namedGroup('patch')!;
```
It has triplication of group names and bangs (`!`) even though named groups are guaranteed to be non-`null`.
What if the static type of `RegExp` actually expressed its groups as a record type and `RegExpMatch` had a getter that returned matches as a record?
```dart
class RegExpWithGroups extends RegExp {
RegExpMatchWithGroups firstMatch(String str);
}
class RegExpMatchWithGroups extends RegExpMatch {
T get groups;
}
final /* inferred: RegExpWithGroups<({String major, String minor, String patch})> */ re =
RegExp(r"(?\d+).(?\d+).(?\d+)");
final m = re.firstMatch(version)!;
final (:major, :minor, :patch) = m.groups;
```
This code is much more type safe and straightforward.
Contributor guide
Research direction
No files or tests are named. Start by reviewing the RegExp and RegExpMatch APIs alongside Dart records and pattern matching, then determine whether the proposed typed capture-group design fits the language specification; done means an agreed, sufficiently specified language change.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- dart
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100