You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl转Dart移植时正则表达式替换结果不一致求助

问题原因

Dart正则表达式中$的匹配行为与Perl存在差异:

  • Perl的$默认匹配字符串末尾,或字符串末尾换行符之前的位置
  • Dart的RegExp默认情况下,$仅匹配整个字符串的绝对末尾,不会识别末尾换行符之前的位置

第二步替换后,字符串变为"this is a line of text ‖ \n",末尾存在换行符。此时Dart的正则r' ‖ $'无法匹配——因为 ‖后紧跟的是换行符,而非字符串的绝对末尾,因此替换无效。

解决方案

将Dart正则中的$替换为\Z,\Z的匹配行为与Perl默认的$一致:匹配字符串末尾,或末尾换行符之前的位置。

修改后的Dart代码
void main() {
  var str = "this is a line of text ‖ ###";
  print("\nIn 1 str=|$str|");
  str = str.replaceAll(RegExp(r'###$'), "\n");
  print("\nIn 2 str=|$str|");
  // 使用\Z替代$,匹配换行符前的位置
  str = str.replaceAll(RegExp(r' ‖ \Z'), "");
  print("\nIn 3 str=|$str|");
}
执行结果
In 1 str=|this is a line of text ‖ ###|

In 2 str=|this is a line of text ‖ 
|

In 3 str=|this is a line of text
|

结果与Perl版本完全一致。

内容的提问来源于stack exchange,提问作者Bid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 20:27:18