Home > Net >  how can I check if any word of a string matches a word in a given list?
how can I check if any word of a string matches a word in a given list?

Time:06-19

for example if I have a string = "I Like To Play Football" and a list = [Car,Ball,Door,Sky] it should give true.

CodePudding user response:

Use any of list

  var list = ["Car","Ball","Door","Sky"];
  String text = "i like to play football";

  if (list.any((item) => text.toLowerCase().contains(item))) {
    //Text has a value from list
  }

CodePudding user response:

Here You Go:

void main() {
  
  final String tempString = "I Like To Play Football";
  final List<String> tempList = ["Car","Ball","Door","Sky"];
  
  for(var i=0; i < tempList.length; i   ) {
    if(tempString.contains(tempList.elementAt(i).toLowerCase())){
      print("Found and its ${tempList[i]}");
    }
  }
}

CodePudding user response:

Regex is your friend here. You can make a simple regex that uses each string in the array as an option (and make it case insensitive) then run the match. I've made an example here in javascript, but it's easy to do in dart

https://api.dart.dev/stable/2.16.1/dart-core/RegExp-class.html

const source = "I Like To Play Football";
const toMatch = ["Car","Ball","Door","Sky"];

let regexString = '';

for (const option of toMatch) {
  //adding | modifier after string. Last one is redundant of course
  //also I'm not checking for special regex characters in toMatch, but that might be necessary.
  regexString  = option   '|';
}

// using slice to remove last |
console.log(regexString.slice(0, -1));

const regexp = new RegExp(regexString.slice(0, -1), 'i');
console.log(source.match(regexp));

CodePudding user response:

Here's a short version:

  var src = 'I Like To Play Football'.split(' ');
  var list = ['Car','Ball','Door','Sky'];
  
  var result = list.any((x) => src.any((y) => y.toLowerCase().contains(x.toLowerCase())));
  
  print(result);
  • Related