首页 > 解决方案 > 每次都可靠地提取 Flutter List 中的字符串

问题描述

所以我有一个非常有趣的练习,我一直在尝试解决一段时间,但还没有提出可靠的解决方案,所以我想你们可以帮助我。我有这个由几个随机自定义部分组成的字符串,例如:

"William\nWilliam description here...\n$170.00 usd") + Uuid().v4();

我需要提取 '$' 和 '.' 之后的部分,在本例中为 170,但它可以是介于两者之间的任何数字。

更新

正如我在上一条评论中所说,如果我想在一个函数中执行此操作(仅查找价格),它可以是这样的:

deleteSumItem(item) {
final regEx = RegExp(r'\$\d+(?:\.\d+)?');
const textToSearch = r'item';
final priceValueMatch = regEx.firstMatch(textToSearch);
print(priceValueMatch.group(0));
_totalPrice.remove(priceValueMatch);
_counter = _counter - priceValueMatch; //getting error here to convert to num
  //but int.parse won't work either, then I get the String error
  //RegExp can't be assigned to paremeter String

}

另外,这个函数为正则表达式返回null,所以我犯了一些错误,有什么想法吗?

deleteSumItem(item) {
final regEx = RegExp(r'\1\d+(?:\.\d+)?');
final priceValueMatch = regEx.firstMatch(r'item');
print('THIS IS REGEX: $priceValueMatch');} //priceValueMatch returns null 

使固定

deleteSumItem(item) {
RegExp regExp = RegExp(r'\^(\d+)\^');
String input = item;
String match = regExp.firstMatch("r" + '"' + input + '"').group(1);
print('Match: $match');
int number = int.parse(match);
print('Number: $number');

_totalPrice.remove(number);
_counter = _counter - number;}

标签: flutterdart

解决方案


假设您可以对我上述评论中的问题回答“是”,您可以简单地使用正则表达式来查找字符串中的价格值:

final regEx = RegExp(r'\$\d+(?:\.\d+)?');
const textToSearch = r'William\nWilliam description here...\n$170.00 cm';
final priceValueMatch = regEx.firstMatch(textToSearch);
print(priceValueMatch.group(0)); // this will print $170.00

正则表达式正在寻找一个美元符号\$,后跟 1 个或多个数字d+,后跟可选的小数点和该小数点后面的可选数字(?:\.\d+)?

这实际上忽略了我上述评论中的很多问题。这只是在您给它的字符串中查找前面有美元符号的价格值。

这是基于您的评论的另一种方法。 这是假设新行字符将始终存在

const textToSearch = 'William\nWilliam description here...\n170.00 cm';
final lines = textToSearch.split('\n'); // Split on new line character
// If your template is always the same,
// then your number will be at the start of line 3:
print(lines[2]); // Will print: 170.00 cm
// If you want just your 170 value then:
final regEx = RegExp(r'\d+'); 
final priceValueMatch = regEx.firstMatch(lines[2]);
final priceInt = int.parse(priceValueMatch.group(0));
print(priceInt); // Will print: 170

推荐阅读