Javascript 用 ',' 分割句子并删除周围的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7695997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split the sentences by ',' and remove surrounding spaces
提问by meandre
I have this code:
我有这个代码:
var r = /(?:^\s*([^\s]*)\s*)(?:,\s*([^\s]*)\s*){0,}$/
var s = " a , b , c "
var m = s.match(r)
m => [" a , b , c ", "a", "c"]
Looks like the whole string has been matched, but where has "b"
gone? I would rather expect to get:
看起来整个字符串已经匹配了,但是哪里"b"
去了?我宁愿期望得到:
[" a , b , c ", "a", "b", "c"]
so that I can do m.shift()
with a result like s.split(',')
but also with whitespaces removed.
这样我就可以m.shift()
处理类似的结果,s.split(',')
但也可以删除空格。
Do I have a mistake in the regexp or do I misunderstand String.prototype.match
?
我在正则表达式中有错误还是我误解了String.prototype.match
?
采纳答案by meandre
so finally i went with /(?=\S)[^,]+?(?=\s*(,|$))/g
, which provides exactly what i need: all sentences split by ',' without surrounding spaces.
所以最后我去了/(?=\S)[^,]+?(?=\s*(,|$))/g
,它提供了我需要的东西:所有的句子都被 ',' 分割,没有周围的空格。
' a, OMG abc b a b, d o WTF foo '.
match( /(?=\S)[^,]+?(?=\s*(,|$))/g )
=> ["a", "OMG abc b a b", "d o WTF foo"]
many thanks!
非常感谢!
回答by CBarr
Here's a pretty simple & straightforward way to do this without needing a complex regular expression.
这是一个非常简单直接的方法,不需要复杂的正则表达式。
var str = " a , b , c "
var arr = str.split(",").map(function(item) {
return item.trim();
});
//arr = ["a", "b", "c"]
The native .map
is supported on IE9 and up: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
.map
IE9 及更高版本支持本机:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Or in ES6+ it gets even shorter:
或者在 ES6+ 中它变得更短:
var arr = str.split(",").map(item => item.trim());
And for completion, here it is in Typescript with typing information
为了完成,这里是带有输入信息的 Typescript
var arr: string[] = str.split(",").map((item: string) => item.trim());
回答by xfg
You can try this without complex regular expressions.
您可以在没有复杂正则表达式的情况下尝试此操作。
var arr = " a , b , c ".trim().split(/\s*,\s*/);
console.log(arr);
回答by Rob W
Short answer: Use m = s.match(/[^ ,]/g);
简短回答:使用 m = s.match(/[^ ,]/g);
您的 RE 没有按预期工作,因为最后一组匹配最近的匹配 (=
c
c
)。如果省略{1,}$
{1,}$
,返回的匹配将是" a , b ", "a", "b"
" a , b ", "a", "b"
。简而言之,您的 RegExp 确实返回与指定组一样多的匹配项unless除非你使用global
global
flag /g
/g
。在这种情况下,返回的列表包含对所有匹配子字符串的引用。To achieve your effect, use:
要达到您的效果,请使用:
m = s.replace(/\s*(,|^|$)\s*/g, "");
This replace replaces every comma (,
), beginning (^
) and end ($
), surrounded by whitespace, by the original character (comma
, or nothing).
此替换将替换每个逗号 ( ,
)、开头 ( ^
) 和结尾 ( $
),用空格包围,替换为原始字符(comma
,或什么都没有)。
If you want to get an array, use:
如果要获取数组,请使用:
m = s.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/);
This RE trims the string (removes all whitespace at the beginning and end, then splits the string by <any whitespace>,<any whitespace>
. Note that white-space characters also include newlines and tabs. If you want to stick to spaces-only, use a space () instead of
\s
.
此 RE 修剪字符串(删除开头和结尾的所有空格,然后将字符串拆分为<any whitespace>,<any whitespace>
。请注意,空格字符还包括换行符和制表符。如果您想仅使用空格,请使用空格 ( )
\s
.
回答by Narendra Yadala
You can do this for your purpose
EDIT: Removing second replace as suggested in the comments.
s.replace(/^\s*|\s*$/g,'').split(/\s*,\s*/)
First replace
trims the string and then the split
function splits around '\s*,\s*'
. This gives output ["a", "b", "c"]
on input " a , b , c "
您可以根据自己的目的执行此操作
编辑:按照评论中的建议删除第二个替换。
s.replace(/^\s*|\s*$/g,'').split(/\s*,\s*/)
首先replace
修剪字符串,然后split
函数围绕 拆分'\s*,\s*'
。这给出["a", "b", "c"]
了输入的 输出" a , b , c "
As for why your regex is not capturing 'b', you are repeating a captured group, so only the last occurrence gets captured. More on that here http://www.regular-expressions.info/captureall.html
至于为什么您的正则表达式没有捕获 'b',您是在重复捕获的组,因此只有最后一次出现才会被捕获。更多关于这里http://www.regular-expressions.info/captureall.html
回答by Dieter Gribnitz
ES6 shorthand:
ES6 简写:
str.split(',').map(item=>item.trim())