简体   繁体   English

按句点分割字符串,但如果句点后有空格则不分割

[英]Split string by period but not if whitespace after period

I have a string like the following and want to split the names into an array using the period character as a separator. 我有一个类似于以下的字符串,并希望使用句点字符作为分隔符将名称拆分为一个数组。 Some names unfortunately also contain the period character which is causing an incorrect split. 不幸的是,某些名称还包含句点字符,这会导致错误的拆分。 I cannot modify the character being used to separate the names. 我无法修改用于分隔名称的字符。

"John Smith.John Mc. Smith.Jim Smith"

Desired output 所需的输出

 ["John Smith","John Mc. Smith","Jim Smith"]

The following regex works well in the editor https://regex101.com/r/oK6iB8/32 以下正则表达式可在编辑器https://regex101.com/r/oK6iB8/32中正常运行

But it does not work in the Chrome console 但它在Chrome控制台中不起作用

"John Smith.John Mc. Smith.Jim Smith".split('\.(?=\S)|:')

https://codepen.io/anon/pen/NogQrQ?editors=1111 https://codepen.io/anon/pen/NogQrQ?editors=1111

Incorrect output 输出错误

["John Smith.John Mc. Smith.Jim Smith"]

Why is this working in the Regex editor but not in the Codepen snippet ? 为什么这在Regex编辑器中有效,但在Codepen代码段中无效?

You can use this regex pattern. 您可以使用此正则表达式模式。

\\.(?!\\s) - . \\.(?!\\s) - . should not be followed by space (negative lookahead) 不应跟space (负超前)

 let str ="John Smith.John Mc. Smith.Jim Smith" let op = str.split(/\\.(?!\\s)/g) console.log(op) 

Why my code didn't worked 为什么我的代码不起作用

split('\\.(?=\\S)|:') because here you're giving \\.(?=\\S)|: as a string not as regular expression. split('\\.(?=\\S)|:')因为在这里您将\\.(?=\\S)|:作为string而不是正则表达式。

 console.log("John Smith.John Mc. Smith.Jim Smith".split(/\\.(?=\\S)|:/)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM