正则表达式删除行末的换行符

时间:2018-09-26 09:08:38

标签: regex python-3.x

为什么此正则表达式不从行尾去除“ \ n”,而是在中间去除它?禁止在任何位置使用“ \ n”。

正则表达式:public PhotoHolder implements MyInterface { // keep extension if you have one Photo photo; Heart heart; // all your previous methods // implement the interface @Override public Photo getPhoto() { return photo; } @Override public Heart getHeart() { return heart; } }

作品:

  • “ \ nabc”

  • “ a \ nb”

不起作用:

  • “ \ n”

  • “ abc \ n”

1 个答案:

答案 0 :(得分:1)

即使在非多行模式下,$也允许跟随单个尾随换行符。 documentation中指出:

  

匹配字符串的末尾,或者匹配换行符之前的末尾   字符串

为避免这种情况,您可以添加前瞻性命令来检查是否没有换行符,例如

^[\w ]*$(?!\n)
相关问题