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

标签 javascript regex

我正在努力避免我们的应用出现不良行为,它需要我清除一些字符串中的不良用法。

假设我有这个字符串

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/

相关文章:

javascript - 如何在 jQuery UI 中创建多范围时间 slider

java - 无法匹配 Mongodb 中的模式搜索

javascript - JS RegExp 删除所有 HTML 标签及其内容?

Javascript 数组索引无法正常工作

javascript - 尝试让 jQuery 在单击时更改不同的 img src

javascript - 无法在 backbone.js 应用程序的绑定(bind)回调中访问 "this"

javascript - 在 Action 重定向 mvc 期间显示等待动画

php - 具有特定长度的任何字符串的正则表达式模式

c# - 正则表达式可以去除什么,例如字符串左边的 "note:"和 "firstName: "?

regex - 在正则表达式中回溯比预期更快