skip to Main Content

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

3

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
  3. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search