Flutter/Dart:正则表达式替换为 2 美元?

Meg*_*ggy 0 regex replaceall dart flutter

我正在尝试使用 Dart 中的 Replaceall 正则表达式方法从 Facebook 图片 URL 中获取 id 号。在下面的代码中我应该使用什么来代替 $2 ?我需要的id号在“asid=”和“&height”之间。

void main() {
 String faceavatar = 'https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=10153806530149154&height=50&width=50&ext=1596623207&hash=AeSi1yDvk8TCqZql';
      String currentavatar = faceavatar.replaceAll(RegExp('(.*asid=)(\d*)height.*'), $2;
  print(currentavatar);
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以尝试:

.*?\basid\b=(\d+).*
Run Code Online (Sandbox Code Playgroud)

上述正则表达式的解释:

  • .*?-懒惰地匹配除之前的换行符之外的所有内容asid
  • \basid\b-asid从字面上匹配。\b代表单词边界。
  • =-=从字面上匹配。
  • (\d+)- 表示第一次或多次捕获组匹配数字。
  • .*-贪婪地执行除换行零次或多次之外的所有操作。
  • $1- 对于更换零件,您可以使用$1match.group(1)

图片展示

您可以在这里找到上述正则表达式的演示

dart 中的示例实现:

void main() {
 String faceavatar = 'https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=10153806530149154&height=50&width=50&ext=1596623207&hash=AeSi1yDvk8TCqZql';
      String currentavatar = faceavatar.replaceAllMapped(RegExp(r'.*?\basid\b=(\d+).*'), (match) {
  return '${match.group(1)}';
});
  print(currentavatar);
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到上述实现的示例运行