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
相关产品推荐
相关产品推荐

