mohamed mostapha
mohamed mostapha

Reputation: 191

flutter check if string starts with RegExp

in flutter if we want to check if a string starts with a specific character...we can achieve that by:


var string = 'Dart';
string.startsWith('D');  // true

what if we want to check if the given string starts with multiple characters....i want to achieve this behaviour:

RegExp myRegExp = ('a-zA-Z0-9');
var string = 'Dart';
string.startsWith('D' + myRegExp);

is the above code is right?!!

my goal is to check if the string starts with a letter i specify...then a RegExp.... not to check if the string starts with 'D' only and thats it...

Upvotes: 1

Views: 10122

Answers (2)

jamesdlin
jamesdlin

Reputation: 89946

what if we want to check if the given string starts with multiple characters....i want to achieve this behaviour:

RegExp myRegExp = ('a-zA-Z0-9');
var string = 'Dart';
string.startsWith('D' + myRegExp);

That won't work. 'D' is a String object, and myRegExp presumably is intended to be a RegExp object. (Your syntax isn't correct; you probably want RegExp myRegExp = RegExp('[a-zA-Z0-9]');.) Both String and RegExp derive from a Pattern base class, but Pattern does not provide operator+, and String.operator+ works only with other Strings. Conceptually it's unclear what adding a String and RegExp should do; return a String? Return a RegExp?

You instead should just write a regular expression that accounts for your first character:

RegExp myRegExp = RegExp('D[a-zA-Z0-9]');

However, if you want the first character to be variable, then you can't bake it into the string literal used for the RegExp's pattern.

You instead could match the two parts separately:

var prefix = 'D';
var restRegExp = RegExp(r'[a-zA-Z0-9]');

var string = 'Dart';
var startsWith =
  string.startsWith(prefix) &&
  string.substring(prefix.length).startsWith(restRegExp);

Alternatively you could build the regular expression dynamically:

var prefix = 'D';
var restPattern = r'[a-zA-Z0-9]';
// Escape the prefix in case it contains any special regular expression
// characters.  This is particularly important if the prefix comes from user
// input.
var myRegExp = RegExp(RegExp.escape(prefix) + restPattern);

var string = 'Dart';
var startsWith = string.startsWith(myRegExp);

Upvotes: 4

Randal Schwartz
Randal Schwartz

Reputation: 44056

I think you'll want something like string.startsWith(RegExp('D' + '[a-zA-Z0-9]'));

Upvotes: 0

Related Questions