Home > Mobile >  How to check if text.contains() contains multiple values
How to check if text.contains() contains multiple values

Time:11-22

I have a text edit controller and I would like to check mutliple characters in the same contains ()

_changeUsernameController.text.contains("a" "b") // what I want

_changeUsernameController.text.contains("a") ||
_changeUsernameController.text.contains("b") // what I have to do

I don't want to write 50 lines so how can I write all in one line like the 'what I want' line Thanks

CodePudding user response:

You can use the any method to write less code for the very same effect:

final subStrings = <String>["a", "b" /* ... */ ];
var result = subStrings.any(_changeUsernameController.text.contains);

Or if you prefer it even shorter:

var result = ["a", "b"].any(_changeUsernameController.text.contains);

CodePudding user response:

Create a function like this:

bool containsAny(String text, List<String> substrings) {
  // returns true if any substring of the [substrings] list is contained in the [text]
  for (var substring in substrings) {
    if (text.contains(substring)) return true;
  }
  return false;
}

Example:

final text = 'Flutter';
final result = containsAny(text, ['c', 'd', 'e']); // true
final result2 = containsAny(text, ['a', 'b', 'c']); // false

CodePudding user response:

You can achieve this by RegExp, try this:

var reg = RegExp(r'(?:a)|(?:b)');
_changeUsernameController.text.contains(reg);

example:

var test1 = 'acc';
var test2 = 'cc';
var test3 = 'ccb';
print(test1.contains(reg)); //true
print(test2.contains(reg)); //false
print(test3.contains(reg)); //true
  • Related