flutter - 每次都可靠地提取 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;}
解决方案
假设您可以对我上述评论中的问题回答“是”,您可以简单地使用正则表达式来查找字符串中的价格值:
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
推荐阅读
- javascript - 在给定数量的堆中加起来的所有可能的术语变化?
- firebase-realtime-database - Cloud Functions 有效,但未显示日志
- r - 使用解析(文本=)
- asp.net-core-3.1 - appsettings.json 复制、传递或发布到 Azure 应用服务配置?
- python - python IBM 量子实验室错误与 qiskit 启用帐户
- tensorflow - ValueError:Conv2D_1 层的输入 0 与层不兼容:预期 ndim=4,发现 ndim=5。收到的完整形状:[None, 3, 210, 160, 3]
- android - 如何在 Android 上仅更改 Spotify 的音量级别?
- python - 为什么有时需要非本地密钥,有时在 python 中不需要
- javascript - 防止 window.XMLHttpRequest.prototype.open 在 JavaScript 中被覆盖
- python-3.x - 当我使用fourcc'X264'时视频不保存