用于删除代码中空格的正则表达式

Regular expression for removing whitespaces in code

如果我有这样的代码:

var     foo       = 5;
if  (  bar > 2) {  bar    += foo;}

应该变成这样:

var foo=5;
if(bar>2){bar+=foo;}

它删除中间没有字母的 space 并避免 keyword/variable 错误。 如果你有两个单词,它们之间的 space 将是一个 whitespace.

\s+(?=[^A-z]) 是我能找到的最接近的,但并不匹配所有 space。

replace(/?=[\w][^\n\t]+/," ") 会将所有多个 space 替换为单个 space,这样您就可以完成一半了。除此之外,如果你真的想要特别的东西,你可以删除所有白色 space 并在所有需要 spaces 的关键词之后添加 spaces ......我不会建议这样做,因为它会破坏包含关键字的变量名的代码。

查看Railssquish方法:

http://apidock.com/rails/String/squish

这似乎有效:

let re = /(?!\b\s*\w)\s*/gm;

编辑:在您的代码中,对于 ES5,只需将 letconst 替换为 var

Regex101

let str = `var     foo       = 5;
if  (  bar > 2) {  bar    += foo;}`;

const re = /(?!\b\s*\w)\s*/gm;

str = str.replace(re, '');

document.body.textContent = str;

也许是这样的:

REST=cat # Whatever the rest of your pipeline is...

( cat <<EOF
var     foo       = 5;
if  (  bar > 2) {  bar    += foo;}
EOF
)\
| tr -s '\t ' " " \
| sed \
    -e 's/\([[:punct:]]\) //g' \
    -e 's/ \([[:punct:]]\)//g' \
| $REST

输出为:

$ sh test.sh
var foo=5;
if(bar>2){bar+=foo;}