1

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...

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your great explanations...many misconceptions have been resolved with this answer
0

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

1 Comment

Sounds promising....its too late here at night so i will try it at morning.....cant wait to give it a try...thanks for you reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.