flutter - 在 Flutter 中提取 Regex 中的字符串并将其转换为 Int
问题描述
我这里有一段 Flutter 代码,它是一个大字符串。每次都会有所不同,但格式会保持不变,因为它是一个模板:
"William\nWilliam description here...\n$^170^ usd" + Uuid().v4()
我想提取170部分,然后将其转换为整数,因此我可以将其从整数列表中删除。我尝试了很多代码,但由于几个原因它不起作用,一个是我无法从^和^之间的字符串中提取实际数字,然后我无法将其转换为整数。这是 try 函数(不完整)。
deleteSumItem(item) {
final regEx = RegExp(r'\^\d+(?:\^\d+)?'); //not sure if this is right regex for the String template
final priceValueMatch = regEx.firstMatch(item); //this doesn't return the particular number extracted
_totalPrice.remove(priceValueMatch); //i get error here that it isn't a int
_counter = _counter - priceValueMatch; //then remove it from interger as int
}
该函数将采用该字符串(“William\nWilliam description here...\n$^170^ usd”+ Uuid().v4())模板(^ ^ 之间的数字会有所不同,但模板是相同的),然后将其转换为整数并作为 int 从列表中删除。
解决方案
尝试以下操作:
void main() {
RegExp regExp = RegExp(r'\^(\d+)\^');
String input = r"William\nWilliam description here...\n$^170^ usd";
String match = regExp.firstMatch(input).group(1);
print(match); // 170
int number = int.parse(match);
print(number); // 170
}
我已经更改了 RegExp,所以它确实正确地捕获了它自己的捕获组中的数字。看起来您在创建 RegExp 的过程中有点困惑,但也可能是我遗漏了有关该问题的一些细节。
推荐阅读
- vim - 粘贴后如何将光标向下移动到文本
- javascript - 隐藏按钮并使其再次可见
- javascript - 将 Base64 图像文件 URI 转换为文件对象
- angular - 角度 - 带有 z-index 的自定义下拉菜单不起作用
- android - 安卓 (Java) | Firestore 安全规则:只允许访问包含用户电子邮件的路径
- php - 当外部在另一张表上时 Laravel 模型查询
- php - 21-04783-85013 在我的 PHP 数组输出中输出为 2.83544E+11(从 CSV 读取)
- python - 傻检查我的简短初学者代码问题
- angular - 将响应分配给角度中的任何数组时出错?
- php - 由 jQuery serialize() / serializearray() 发布,不包括 textarea