如何在 JavaScript 中第一次出现多个子字符串之一时分割字符串?
给定字符串
s1 = "abcfoodefbarghi"
以及
s2 = "abcbardefooghi"
如何将 s1 拆分为“abc”和“defbarghi” 和 s2 到“abc”和“defooghi” 也就是说:在第一次出现字符串“foo”或“bar”时将字符串分成两部分
我想这可以用 s.split(/regexp/) 来完成,但是应该做什么这个正则表达式是?
Given strings
s1 = "abcfoodefbarghi"
and
s2 = "abcbardefooghi"
How can I split s1 into "abc" and "defbarghi"
and s2 into "abc" and "defooghi"
That is: split a string into two on the first occurrence of either one of strings "foo" or "bar"
I suppose this could be done with s.split(/regexp/)
, but what should this regexp be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以这种方式使用正则表达式:
RE 的解释:
[\S\s]*?
匹配足够多的字符来匹配 RE 的下一部分,即(foo|bar )
“foo”或“bar”[\S\s]*
匹配其余字符RE 的一部分周围的括号创建一个组,以便分组匹配可以引用,而
(?:)
创建一个不可参考组。Use a Regular Expression in this way:
Explanation of the RE:
[\S\s]*?
matches just enough characters to match the next part of the RE, which is(foo|bar)
either "foo", or "bar"[\S\s]*
matches the remaining charactersParentheses around a part of a RE creates a group, so that the grouped match can be referred, while
(?:)
creates a non-referrable group.想法是用特殊(不可见)字符串替换第一次出现,然后针对该字符串进行拆分。
idea is replace the first occurrence with a special(invisible) String, and then split against this string.