我正在努力避免我们的应用出现不良行为,它需要我清除一些字符串中的不良用法。
假设我有这个字符串
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'
),使用 Negative lookahead(比如 - (?!\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"
关于javascript - 正则表达式处理标点符号和文本改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27642600/