3

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

2
  • You can use Regex maybe? Commented Nov 21, 2022 at 14:08
  • Can you write the code please ? Commented Nov 21, 2022 at 14:09

3 Answers 3

6

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

Comments

1

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

1 Comment

Thanks but I used @nvoigt solution
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

3 Comments

It's not working with String oui = 'Tamara'; for exemple
I update my answer, remove ^ from regex. @Boatti
Yes it was that thanks dude

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.