首页 > 解决方案 > 在 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 从列表中删除。

标签: flutterdart

解决方案


尝试以下操作:

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 的过程中有点困惑,但也可能是我遗漏了有关该问题的一些细节。


推荐阅读