首页 > 解决方案 > 按句点分割字符串,但如果句点后有空格则不分割

问题描述

我有一个如下所示的字符串,并希望使用句点字符作为分隔符将名称拆分为一个数组。不幸的是,某些名称还包含导致不正确拆分的句点字符。我无法修改用于分隔名称的字符。

"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 片段中无效?

标签: javascriptregex

解决方案


您可以使用此正则表达式模式。

\.(?!\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)|:/))


推荐阅读