用','拆分句子并删除周围的空格 [英] Split the sentences by ',' and remove surrounding spaces
本文介绍了用','拆分句子并删除周围的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码:
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"]
看起来像整个字符串已匹配,但哪里有b
消失了?我希望得到:
Looks like the whole string has been matched, but where has "b"
gone? I would rather expect to get:
[" a , b , c ", "a", "b", "c"]
这样我就可以 m.shift()
结果如 s.split(',')
,但也删除了空格。
so that I can do m.shift()
with a result like s.split(',')
but also with whitespaces removed.
我是否在regexp中有错误或者我误解了 String.prototype.match
?
Do I have a mistake in the regexp or do I misunderstand String.prototype.match
?
推荐答案
所以最后我去了 /(?= \S)[^,] +?(?= \ * *(,| $))/ g
,它提供了我所需要的:所有句子用','分隔,没有周围的空格。
so finally i went with /(?=\S)[^,]+?(?=\s*(,|$))/g
, which provides exactly what i need: all sentences split by ',' without surrounding spaces.
' a, OMG abc b a b, d o WTF foo '.
match( /(?=\S)[^,]+?(?=\s*(,|$))/g )
=> ["a", "OMG abc b a b", "d o WTF foo"]
非常感谢!
这篇关于用','拆分句子并删除周围的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文