如何在dart中使用正则表达式对字符串列表进行排序? [英] How do I sort a string list using regular expressions in dart?
本文介绍了如何在dart中使用正则表达式对字符串列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我实际上是在寻找除.sort()之外的另一种对字符串列表进行排序的方法出于我的目的使用它给我 type'_SecItem'不是'Comparable< dynamic>'
类型的子类型我正在尝试通过字符串前面的数字对字符串列表进行排序.像这样:
I'm essentially looking for another way to sort a string list besides the .sort()
Using that for my purpose gives me type '_SecItem' is not a subtype of type 'Comparable<dynamic>'
I'm trying to sort a string list by the numerical numbers in front of the strings. Something like:
List<String> hi = ['05stack', '03overflow', '01cool','04is', '02uToo'];
对此:
['01cool', '02uToo', '03overflow', '04is', '05stack']
推荐答案
具有提取数字之类的功能
With a function to extract the number like
int extractNumber(String srt){
RegExp regex = new RegExp(r"(\d+)");
return regex.allMatches(srt).toList().map((m){
return srt.substring(m.start, m.end);
}).toList().map((v)=>int.parse(v)).first;
}
void main(){
List<String> test = ['05stack', '03overflow', '01cool','04is', '02uToo'];
test.sort((a, b)=>extractNumber(a)>extractNumber(b) ? 1 : -1);
print(test);
}
这篇关于如何在dart中使用正则表达式对字符串列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文