简体   繁体   English

表达式在每行末尾添加逗号。 虽然不应该做最后一行

[英]expression appends comma to the end of every line. Should not do the last line though

I have this pattern which works well for adding a comma to the end of every line. 我有这种模式,非常适合在每行末尾添加逗号。

str.replace(/(.+)\s*?($|\n)/gm, "$1, $2")

But I cannot understand how to change it so that it will not put a comma on the last line. 但是我不知道如何更改它,以便它不会在最后一行加上逗号。 Especially considering the last line could end in a line break. 特别是考虑到最后一行可能会以换行符结尾。 I guess I could search for the comma after the replace is done and just remove the last comma, but that seems sort of weak. 我猜我可以在替换完成后搜索逗号,然后删除最后一个逗号,但这似乎有点弱。 Is there some way I can change this pattern so that it never appends a comma to the last line? 有什么办法可以更改此模式,以便它永远不会在最后一行添加逗号?

Just remove the $ from there, and add it as negative look ahead after \\n : 只需从此处删除$ ,然后将其添加为\\n后的负数即可:

str.replace(/(.+)\s*?(\n(?!$))/gm, "$1, $2")

This will only add a comma before \\n if it is not at the end of the string. 如果它不在字符串的末尾,则只会在\\n之前添加一个逗号。

Why not think in a bit different and very easy : 为什么不这么想却又很简单:

\\r?\\n(.+) \\ r?\\ n(。+)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM