Skip to content

Commit

Permalink
Add ExactMatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
kaboc committed Dec 28, 2023
1 parent 2107733 commit c05b76b
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/src/preset_matchers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,24 @@ class TelMatcher extends TextMatcher {
r')(?!\d)',
]);
}

/// A variant of [TextMatcher] for parsing strings that exactly match
/// any of the strings in the passed list.
///
/// {@template textParser.ExactMatcher}
/// ```dart
/// TextParser(
/// matchers: [
/// ExactMatcher(['e.g.', 'C++']),
/// ],
/// )
/// ```
/// {@endtemplate}
class ExactMatcher extends TextMatcher {
/// Creates an [ExactMatcher] for parsing strings that exactly match
/// any of the strings in the passed list.
///
/// {@macro textParser.ExactMatcher}
ExactMatcher(Iterable<String> strings)
: super(strings.map(RegExp.escape).join('|'));
}
29 changes: 29 additions & 0 deletions test/matchers/exact_matcher_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import 'package:test/test.dart';

import 'package:text_parser/text_parser.dart';

extension on ExactMatcher {
RegExp toRegExp() {
return RegExp(pattern);
}
}

void main() {
test('Strings using reserved characters match exactly same strings', () {
const input = 'Assembly BASIC C++? Dart (^*^)/';
final regExp = ExactMatcher(const ['(^*^)/', 'C++']).toRegExp();
final matches = regExp.allMatches(input).toList();
expect(matches, hasLength(2));
expect(input.substring(matches[0].start, matches[0].end), 'C++?');
expect(input.substring(matches[1].start, matches[1].end), '(^*^)/');
});

test('Reserved characters are escaped and used as ordinary characters', () {
const input = 'ABCDEF AB.DE+';
final regExp = ExactMatcher(const ['B.D', 'E+']).toRegExp();
final matches = regExp.allMatches(input).toList();
expect(matches, hasLength(2));
expect(input.substring(matches[0].start, matches[0].end), 'B.D');
expect(input.substring(matches[1].start, matches[1].end), 'E+');
});
}

0 comments on commit c05b76b

Please sign in to comment.