Prexp (Path to regular expression) is a Dart package that converts a path to a regular expression.
import 'package:prexp/prexp.dart';
void main() {
final String route = r'/users/:name';
final Prexp prexp = Prexp.fromString(route);
print(prexp.hasMatch('/users/odroe')); // true
final PathMatcher matcher = PathMatcher.fromPrexp(prexp);
print(matcher('/users/odroe')); // (PrexpMatch(/users/Seven, {name: Seven}))
final PathBuilder builder = PathBuilder.fromPath(route);
print(builder({'name': 'odroe'})); // /users/odroe
print(Prexp.parse(
route)); // [StringPrexpToken(/users), MetadataPrexpToken({"name":"name","prefix":"/","suffix":"","pattern":"[^\\/#\\?]+?","modifier":""}]
}
Add this to your package's pubspec.yaml file:
dependencies:
prexp: latest
Or install it from the command line:
dart pub add prexp
The Prexp.parse
static utility to create an list of PrexpToken
from a path.
final Iterable<PrexpToken> tokens = Prexp.parse('/users/:name');
delimiter
- The delimiter between segments. Defaults to/#?
.prefixes
- The prefixes to use when parsing a path. Defaults to./
.
Prexp
implements the RegExp
interface and is compatible with RegExp
. The only difference between Prexp
and RegExp
is that Prexp
contains the parameter source information of path.
final Prexp prexp = Prexp.fromString('/users/:name');
print(prexp.hasMatch('/users/odroe')); // true
print(prexp is RegExp); // true
print(prexp.metadata); // MetadataPrexpToken({"name":"name","prefix":"/","suffix":"","pattern":"[^\\/#\\?]+?","modifier":""})
final Prexp prexp = Prexp.fromString('/users/:name');
final RegExp regexp = ...;
final Prexp prexp = Prexp.fromRegExp(regexp);
final Iterable<PrexpToken> tokens = Prexp.parse('/users/:name');
final Prexp prexp = Prexp.fromTokens(tokens);
The PathBuilder
class is used to build a path from a map of parameters.
final PathBuilder builder = PathBuilder.fromPath('/users/:name');
print(builder({'name': 'odroe'})); // /users/odroe
final Iterable<PrexpToken> tokens = Prexp.parse('/users/:name');
final PathBuilder builder = PathBuilder.fromTokens(tokens);
print(builder({'name': 'odroe'})); // /users/odroe
The PathMatcher
class is used to match a path against a route.
final Prexp prexp = Prexp.fromString('/users/:name');
final PathMatcher matcher = PathMatcher.fromPrexp(prexp);
print(matcher('/users/odroe')); // (PrexpMatch(/users/odroe, {name: odroe}))
final RegExp regexp = ...;
final Iterable<MetadataPrexpToken> metadata = ...;
final PathMatcher matcher = PathMatcher.fromRegExp(regexp, metadata);
print(matcher('/users/odroe'));
final PathMatcher matcher = ...;
final Iterable<PrexpMatch> matches = matcher('/users/odroe');
print(matches); // (PrexpMatch(/users/odroe, {name: odroe}))
Note: If the path does not match the route, the
PathMatcher
returns an empty list.