![](/img/trans.png)
[英]Split a string into an array of words, punctuation and spaces in JavaScript
[英]Javascript: Remove string punctuation and split into words?
抱歉,以前是否有人问过这个问题,但是我想从这样的字符串中获取单词数组:
"Exclamation! Question? \"Quotes.\" 'Apostrophe'. Wasn't. 'Couldn't'. \"Didn't\"."
该数组应该看起来像这样:
[
"exclamation",
"question",
"quotes",
"apostrophe",
"wasn't"
"couldn't",
"didn't"
]
目前,我正在使用此表达式:
sentence.toLowerCase().replace(/[^\w\s]/gi, "").split(" ");
问题是,它去除了诸如“不是”之类的单词中的撇号,将其变成了“不是”。
我不知道如何在这样的词中保留撇号。
任何帮助将不胜感激!
var sentence = "Exclamation! Question? \\"Quotes.\\" 'Apostrophe'. Wasn't. 'Couldn't'. \\"Didn't\\"."; console.log(sentence.toLowerCase().replace(/[^\\w\\s]/gi, "").split(" "));
解决您自己的解决方案将很棘手,但是您可以通过以下方式考虑撇号:
sentence = `"Exclamation! Question? \\"Quotes.\\" 'Apostrophe'. Wasn't. 'Couldn't'. \\"Didn't\\"."`; console.log( sentence.match(/\\w+(?:'\\w+)*/g) );
注意:从?
更改了量词 *
允许一个单词中包含多个'
。
@revo的答案看起来不错,这是另一个应该也起作用的选项:
const input = "Exclamation! Question? \\"Quotes.\\" 'Apostrophe'. Wasn't. 'Couldn't'. \\"Didn't\\"."; console.log(input.toLowerCase().match(/\\b[\\w']+\\b/g));
说明:
\\b
匹配单词的开头/结尾, [\\w']+
匹配任何字母,数字,下划线或引号(要省略下划线,可以改用[a-zA-Z0-9']
), /g
告诉正则表达式捕获与该模式匹配的所有匹配项(而不仅仅是第一个)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.