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

Regex to deal with punctuation and text improvement

本文关键字:文本 标点符号 处理 正则表达式      更新时间:2023-09-26

我试图避免我们应用程序上的不良行为,它需要我从不良使用中清除一些字符串。

假设我有这个字符串

str = "This is a very bad BEHAVIOR !!!Don't you think So ????";

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

所以我的字符串应该是

str = "This is a very bad behavior! Don't you think so?"

我在stackoverflow上发现了一个示例代码,可以在标点符号后添加一个空格:

str.replace(/[,.!?:;](?='S)/g, '$& ');

但这并不能帮助我删除标点符号前的空格

帮助找到合适的正则表达式将不胜感激

似乎有效 -

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?"

编辑:

关于使用小数点的情况(如大小写 - '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"