how can I check if any word of a string matches a word in a given list? - flutter

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

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
}

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]}");
}
}
}

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));

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

Strip any hashtags at the end of a string in Dart

I'm currently extracting hashtags from a string and adding them to an array but how can I remove them from the string as well provided they are located by the end?
For example:
// Random string with tags
String message = "Hello #tag1 and #tag2 the end #tag3 #tag4";
RegExp regex = RegExp(r"\B#\w\w+");
List<String> tags = [];
// Add each tag to list
regex.allMatches(message).forEach((match){
tags.add(match.group(0)!);
});
How to remove #tag3 #tag4 from the original string so it's updated to look:
Hello #tag1 and #tag2 the end
The only reason I'm keeping #tag1 and #tag2 is because it would look weird if they were taken out since it's within a sentence. Note that the string can be anything.
Original code taken from here.
Try this:
String text = "Test #tag1 and #tag2 end #tag3 #tag4";
String resultText = "";
var l = text.split(" ");
int index = l.lastIndexWhere((element) => !element.contains('#'));
l.removeRange(index + 1, l.length);
resultText = l.join(' ');
print("resultText= $resultText"); //resultText= Test #tag1 and #tag2 end

How to remove first word from a sentence in flutter - dart

Looking for the same solution that was given in swift here - How to remove first word from a sentence in swift.
Anyone can help?
void main() {
String words = "hello world everyone";
List<String> word_l = words.split(" ");
String word = word_l.sublist(1,word_l.length).join(" ");
print(word);
}
Use as above code to remove first word from words. This work for multiple words more than 2.
You could just do this:
void main() {
var data = 'CITY Singapore';
data = data[0];
print(data);
}

Find the most used word in the text in flutter

I'm calculating how many different words there are. How can I find the most used word in the text. How can I add this to the code.
int kacFarkliKelime(String metin) {
String yeniMetin = metin.replaceAll(RegExp(r'[^\w\s]+'), "");
List<String> liste = yeniMetin.split(
" ",
);
List farklilar = [];
liste.forEach((element) {
String sorgulanan = element.toLowerCase();
if (!farklilar.contains(sorgulanan)) {
farklilar.add(sorgulanan);
}
});
if(farklilar[0])
return farklilar.length;
}
I'd build a Map<String, int> that'd count each word as it is seen, then get a list of keys sorted by descending value order. (There's a few handy "sort by" functions in package:collection to help with that.) The code for that would look like:
var words = (use a regex to extract words);
var count = <String,int>{};
for (final w in words) {
count[w] = 1 + (count[w] ?? 0);
}
var ordered = count.keys.toList();
ordered.sort((a, b) => count[b].compareTo(count[a]));
Now the first element of ordered is the word with the most appearances in the text.

Extract number and separate with comma from list in Flutter

List listFinal = [];
So listFinal have values from multiple list inside like below.
[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]]
How do I make this list so that it only extract numbers and separate with comma?
End result should be like
[1113335555, 2223334555, 5553332222]
I can think of trimming or regexp but not sure how to pull this off.
many thanks.
Try this
void main() {
List<String> numberList=[];
List<List<dynamic>> demoList=[["test: 111-333-5555", "test2: 222-333-4555"], ["test3: 555-333-2222"]];
for(int i=0;i<demoList.length;i++){
numberList.addAll(demoList[i].map((e) => e.toString().split(":")[1].replaceAll("-", "")).toList());
}
print(numberList.toString());
}
Here is an example to get you started. This doesn't handle things like malformed input strings. First step is to "flatten" the list with .expand, and then for each element of the flattened iterable use a regex to extract the substring. Other options might include using .substring to extract exactly the last 12 characters of the String.
You can see this in action on dartpad.
void main() {
final input = [
['test: 111-333-5555', 'test2: 222-333-4555'],
['test3: 555-333-2222']
];
final flattened = input.expand((e) => e); // un-nest the lists
// call extractNumber on each element of the flattened iterable,
// then collect to a list
final result = flattened.map(extractNumber).toList();
print(result);
}
final _numberRegExp = RegExp(r'.*: ([\d-]+)$');
int extractNumber(String description) {
var numberString = _numberRegExp.firstMatch(description).group(1);
return int.parse(numberString.replaceAll('-', ''));
}
Let's do this in a simple way.
List<List<String>> inputList = [
["test: 111-333-5555", "test2: 222-333-4555"],
["test3: 555-333-2222"]
];
List resultList = [];
print('Input List : $inputList');
inputList.forEach((subList){
subList.forEach((element){
var temp = element.split(' ')[1].replaceAll('-', '');
resultList.add(temp);
});
});
print('Output List : $resultList');
Here I have taken your list as inputList and stored the result in resultList.
For each element of inputList we get a sub-list. I have converted the elements of that sub-list into the needed format and added those into a List.
Happy Coding :)

jquery and pathname ... again ! ;-)

I'm trying the slug of my url at the end.
If url is one of the followings, I want to get "link1" only (no quotes).
http://www.site.com/link1
http://www.site.com/category/link1
http://www.site.com/myblog/category/link1
This is what I have but only the 2 firsts work.
$(".ajaxed").live("click", function(event) {
var post_slug = $(this)[0].pathname.substring($(this)[0].pathname.lastIndexOf("/")).replace(/^\//, "");
alert(post_slug);
$.address.crawlable(true).value(post_slug);
$(this).load("ajax/",{slug:post_slug}, function(){
});
return false;
});
Can I get help with the syntax please? Many thanks for your time and help.
Why can't you just split the string and return the very end?
var post_slug_array = $(this)[0].pathname.split('/');
var post_slug = post_slug_array[post_slug_array.length - 1];
I've try run:
t = "http://www.site.com/myblog/category/link1";
t.substring(t.lastIndexOf("/")).replace(/^\//,"");
console.log(t);
and I got link1. It's right, isn't it? so what's the problem on earth?
Not sure exactly what you are after, but trim the trailing slash. How do you want to handle querystrings? Your current code includes them.
http://jsfiddle.net/ppyJr/1/
//test cases
var paths = new Array(
'http://www.site.com/link1',
'http://www.site.com/myblog/category/link1',
'http://www.site.com/myblog/category/link1?querystring',
'http://www.site.com/myblog/category/link1/',
'http://www.site.com/myblog/category/link1/?querystring'
);
for (var i = 0; i < paths.length; i++) {
//trim trailing slash
var x = paths[i].replace(/\/$/, "");
//get trailing item
var post_slug = x.substring(x.lastIndexOf("/") + 1, x.length);
alert(post_slug);
}