从字符第一次出现的地方分割字符串
我在日志文件中有多行这种格式的文本:
topic, this is the message part, with, occasional commas.
如何从第一个逗号中分割字符串,以便将主题和消息的其余部分放在两个不同的变量中?
我尝试过使用这种拆分,但是当消息部分中有更多逗号时它不起作用。
[topic, message] = whole_message.split(",", 2);
I have multiple lines of text in log files in this kind of format:
topic, this is the message part, with, occasional commas.
How can I split the string from the first comma so I would have the topic and the rest of the message in two different variables?
I've tried using this kind of split, but it doesn't work when there's more commas in the message part.
[topic, message] = whole_message.split(",", 2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用正则表达式来获取“除了第一个逗号之外的所有内容”。因此:
[1]
将是主题,[2]
将是消息。Use a regex that gets "everything but the first comma". So:
[1]
will be the topic,[2]
will be the message.这里!
Here!
这种分解赋值在 Javascript 中不起作用(目前)。试试这个:
编辑 - 好的,所以“split()”有点坏了;试试这个:
That sort of decomposing assignment doesn't work in Javascript (at the present time). Try this:
edit — ok so "split()" is kind-of broken; try this:
javascript 的
String.split()
方法已损坏(至少如果您期望其他语言的split()
方法提供相同的行为)。这种行为的一个例子:
并不
像你想象的那样。
试试这个 split 函数:
javascript's
String.split()
method is broken (at least if you're expecting the same behavior that other language'ssplit()
methods provide).An example of this behavior:
and not
like you'd expect.
Try this split function instead:
(除非你喜欢以复杂的方式做事)
(unless you like doing things complicated ways)
为什么不用逗号分割,将 [0] 项作为主题,然后从原始字符串中删除主题(+,)?
你可以:(
使用prototype.js)
(使用jQuery)
或者更快,使用josh.trow
Why not split by comma, take the [0] item as topic then remove the topic(+,) from the original string ?
You could:
(using prototype.js)
(using jQuery)
Or quicker, go with josh.trow
输出 arr 应该是:[“主题”,“这是消息部分,偶尔有逗号。”]
output arr should be: ["topic", "this is the message part, with occasional commas."]
使用
/,(.*)/
或更确切地说/, *(.*)/
进行拆分以考虑逗号后面的空格示例:
Split using
/,(.*)/
or rather/, *(.*)/
to account for the space after the commaExample: