正则表达式处理标点符号和文本改进

Tou*_*eur 3 javascript regex

我试图避免我们的应用程序上的不良行为,它需要我清理一些不良用法的字符串.

我们说我有这个字符串

str = "This is a very bad BEHAVIOR !!!Don't you think So ????";
Run Code Online (Sandbox Code Playgroud)

我需要应用3条规则: - 没有喊叫模式(不是所有CAPS) - 在标点符号前删除空格,然后添加一个空格 - 删除所有重复的标点符号

所以我的字符串应该是

str = "This is a very bad behavior! Don't you think so?"
Run Code Online (Sandbox Code Playgroud)

我在stackoverflow上找到了一个示例代码,用于在标点符号后添加一个空格:

str.replace(/[,.!?:;](?=\S)/g, '$& ');
Run Code Online (Sandbox Code Playgroud)

但这并没有帮助我在标点符号之前删除空格

找到合适的正则表达式,帮助真的很感激

Kam*_*eha 5

这似乎有效 -

str.replace(/\s*([,.!?:;])[,.!?:;]*\s*/g,'$1 ').  //This removes all the punctuations
replace(/(?:^|[^a-z])([A-Z]+)(?:[^a-z]|$)/g,function(v){return v.toLowerCase();}). //Upper case to lower case
replace(/\s*$/,"") //Trimming the right end

OUTPUT:
"This is a very bad behavior! Don't you think So?"
Run Code Online (Sandbox Code Playgroud)

编辑:

关于使用小数点的情况(如情况 - 'This is 14.5 degree'),使用负前瞻(如此 - (?!\d+))应该有效.

例如 -

str = 'This is 14.5 degree'
str.replace(/\s*(?!\d+)([,.!?:;])[,.!?:;]*(?!\d+)\s*/g,'$1 ').  //This removes all the punctuations
replace(/(?:^|[^a-z])([A-Z]+)(?:[^a-z]|$)/g,function(v){return v.toLowerCase();}). //Upper case to lower case
replace(/\s*$/,"") //Trimming the right end

OUTPUT:
"This is 14.5 degree"
Run Code Online (Sandbox Code Playgroud)