我有一组结构相似的字符串,我试图通过JavaScript分成不同的部分。
示例字符串:
JR。 Kevin Hooks,Irene Cara,Moses Gunn,Robert Hooks,Ernestine Jackson,JoséFeliciano。 Lorem ipsum dolor坐下来,精致的adipistur elit。 Curabitur ullamcorper sodales nulla id hendrerit。
理想输出:
[
"Jr. Kevin Hooks","Irene Cara",…
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur
ullamcorper sodales nulla id hendrerit."
]
我的第一个念头就是'。 '将文本块中的名称分隔到末尾,然后将名称组拆分为',',但因为某些名称就像'Jr. Kevin Hooks'和文本块也包含'。 '那种方法失败了。使用','作为键也会失败,因为文本块包含','。
有关如何完成此任务的任何建议?
非常感谢!
答案 0 :(得分:1)
如果我们可以假设:
然后你可以使用这个正则表达式:
/([a-z]{1,3}\.|[^\s,.]+)(\s+([a-z]{1,3}\.|[^\s,.]+))*(?=[,.])|\..*$/ig
var text = 'Jr. Kevin Hooks, Irene Cara, Moses Gunn, Robert Hooks, Ernestine Jackson, José Feliciano. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ullamcorper sodales nulla id hendrerit.'
var result = text.match(/([a-z]{1,3}\.|[^\s,.]+)(\s+([a-z]{1,3}\.|[^\s,.]+))*(?=[,.])|\..*$/ig);
// Optionally remove the point at the start of the last match:
if (result) result.push(result.pop().replace(/^\.\s*/, ''));
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

[a-z]{1,3}\.
匹配一到三个拉丁字符,后跟一个点[^\s,.]+)
匹配一个或多个不是空格,逗号或点( | )
:要么必须匹配:以上两种模式以这种方式组合,这意味着名称中的单词必须是最多三个拉丁字母后跟一个点,或任何数量的非白色 - 空间,不包括逗号和点。(\s+([a-z]{1,3}\.|[^\s,.]+))*
:可选(*
)允许更多类似的字词:匹配一个或多个空格,并在开头重复模式。(?=[,.])
这一系列的单词必须以逗号或点结尾,而不是抓住(仅向前看):由于没有抓住这一点,我们肯定知道开始的模式不再匹配了,那就是下一个模式将完成这项工作的时间:\..*$
匹配一个文字点,然后匹配字符串末尾的任何字符($
)最后一个文本块之前的点也包含在最后一个匹配项中,因此您可能需要单独删除它(请参阅代码段)。