正则表达式删除Java脚本中的空格,空白行和最后一个换行符 [英] Regex to remove white spaces, blank lines and final line break in Javascript

查看:58
本文介绍了正则表达式删除Java脚本中的空格,空白行和最后一个换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我在使用正则表达式时遇到了麻烦.

Ok guys, I'm having a hard time with regex..

这就是我需要的...获取文本文件,删除这些行的开头和结尾的所有空白行和空格,要删除的空白行在文件末尾还包括一个空行(全文末尾的\ n)

Here's what I need... get a text file, remove all blank lines and white spaces in the beginning and end of these lines, the blank lines to be removed also include a possible empty line at the end of the file (a \n in the end of the whole text)

所以我的脚本是:

quotes.replace(/^\s*[\r\n]/gm, "");

替换效果很好,但是每行末尾留了一个空格,并且不会删除最后的换行符.

This replaces fairly well, but leaves one white space at the end of each line and doesn't remove the final line break.

所以我想使用这样的东西:

So I thought using something like this:

quotes.replace(/^\s*[\r\n]/gm, "").replace(/^\n$/, "");

第二个替换"会从整个字符串中删除最后一个\ n,如果存在..但不起作用.

The second "replace" would remove a final \n from the whole string if present.. but it doesn't work..

所以我尝试了这个:

quotes.replace(/^\s*|\s*$|\n\n+/gm, "")

删除换行符,但是在中间出现换行符时加入一些行:

Which removes line breaks but joins some lines when there is a line break in the middle:

这样
1
2
3

4

so that
1
2
3

4

将返回以下行:

["1","2","34"]

["1", "2", "34"]

你们能帮我吗?

推荐答案

由于听起来您必须在单个正则表达式中完成所有操作,因此请尝试以下操作:

Since it sounds like you have to do this all in a single regex, try this:

quotes.replace(/^(?=\n)$|^\s*|\s*$|\n\n+/gm,"")

我们正在做的工作是创建一个不捕获任何内容的组,但阻止换行本身被占用.

What we are doing is creating a group that captures nothing, but prevents a newline by itself from getting consumed.

这篇关于正则表达式删除Java脚本中的空格,空白行和最后一个换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆