简体   繁体   English

用空格和破折号分割字符串

[英]Split string by whitespace and dashes

What is the best way to split a string up into an array of 'words'. 将字符串分成“单词”数组的最佳方法是什么。 Splitting by whitespace but also by dashes, where a dash becomes part of the previous 'word'. 用空格分隔,但也用破折号分隔,其中破折号成为前一个“单词”的一部分。

Example: 例:

"This is an example-string to “这是一个示例字符串

demo what I mean" 演示我的意思”

[ "This", "is" , "an" , "example-" , "string" , "to" , "demo" , "what" , "I" , "mean" ] [“ This”,“ is”,“ an”,“ example-”,“ string”,“ to”,“ demo”,“ what”,“ I”,“ mean”]

Edit: I'm an idiot - It is this: 编辑:我是一个白痴-这是:

someString.replace(/-/g, "- ").split(/[\s]/); // retain dashes

Splitting won't work if the delimiter should stay in the result, because the delimiter is always consumed. 如果定界符应保留在结果中,则拆分将不起作用,因为定界符总是被使用。

Use .match instead: 使用.match代替:

"This is an example-string to demo what I mean".match(/[^\s-]+-?/g);
// ["This", "is", "an", "example-", "string", "to", "demo", "what", "I", "mean"]

This regexp matches one or more characters that are not spaces/dashes, and an optional dash following it. 此正则表达式匹配一个或多个非空格/破折号以及其后的可选破折号。 With the g flag, all matches are returned. 使用g标志,将返回所有匹配项。

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

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