javascript - 按句点分割字符串,但如果句点后有空格则不分割
问题描述
我有一个如下所示的字符串,并希望使用句点字符作为分隔符将名称拆分为一个数组。不幸的是,某些名称还包含导致不正确拆分的句点字符。我无法修改用于分隔名称的字符。
"John Smith.John Mc. Smith.Jim Smith"
期望的输出
["John Smith","John Mc. Smith","Jim Smith"]
以下正则表达式在编辑器中运行良好 https://regex101.com/r/oK6iB8/32
但它在 Chrome 控制台中不起作用
"John Smith.John Mc. Smith.Jim Smith".split('\.(?=\S)|:')
https://codepen.io/anon/pen/NogQrQ?editors=1111
输出不正确
["John Smith.John Mc. Smith.Jim Smith"]
为什么这在 Regex 编辑器中有效,但在 Codepen 片段中无效?
解决方案
您可以使用此正则表达式模式。
\.(?!\s)
-.
后面不应跟space
(负前瞻)
let str ="John Smith.John Mc. Smith.Jim Smith"
let op = str.split(/\.(?!\s)/g)
console.log(op)
为什么我的代码不起作用
split('\.(?=\S)|:')
因为在这里你给出\.(?=\S)|:
的string
不是正则表达式。
console.log("John Smith.John Mc. Smith.Jim Smith".split(/\.(?=\S)|:/))
推荐阅读
- vba - 我需要帮助,将复制的项目与 Excel 中的 Powerpoint 对齐
- c# - 为什么使用 Blazor OnInitialized 方法返回基方法
- azure - Azure 应用程序网关入口控制器未到达服务(CLusterIP)
- django - 使用 dj_rest_auth 的 Django REST 社交登录不会对用户进行身份验证
- c++ - 获取存储在 LLVM 变量中的数据
- java - ClassCastException 即使在使用泛型之后
- tkinter - 使用 GitHub Actions 测试 tkinter/tcl GUI?
- python - 运行“$ python manage.py collectstatic --noinput”时出错。即使我设置了 STATIC_ROOT 和 STATIC_FILES_DIRS
- angularjs - 缺少 app 文件夹的新 Angular 项目
- substrate - 遵循 Add a Pallet to Your Runtime 教程时出现“外部失败”