Reputation: 691
I want to check if a string only contains:
in Flutter, I tried the following to get only the letters but even if other characters are there it returns true if it contains a letter:
String mainString = "abc123";
print(mainString.contains(new RegExp(r'[a-z]')));
As I told it returns true
since it contains letters, but I want to know if it only contains letters.
Is there a way to do that?
Upvotes: 7
Views: 18620
Reputation: 90175
The problem with your RegExp
is that you allow it to match substrings, and you match only a single character. You can force it to require that the entire string be matched with ^
and $
, and you can match against one or more of the expression with +
:
print(RegExp(r'^[a-z]+$').hasMatch(mainString));
To match all the characters you mentioned:
print(RegExp(r'^[A-Za-z0-9_.]+$').hasMatch(mainString));
Upvotes: 27
Reputation: 2171
the basic way of doing this is as follow:
// for example
List<String> validChar = ["1", "2", "3", "t"];
// given text
String x = "t5";
bool valid = true;
for(int i=0; i<x.length; i++){
if(!validChar.contains(x[i])){
valid = false;
}
}
print(valid);
just change the x
and validChar
as your need.
Upvotes: 2