因此,我已经尝试了一段时间,这是一个非常有趣的练习,但是还没有提出一个可靠的解决方案,所以我认为你们可以帮助我。我有一个由几个随机的自定义部分组成的String,例如:
"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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句