抓住方括号之间的第三个片段
仍然完全被正则表达式和方括号所困扰。希望有人可以帮助我。
假设我有一个像这样的字符串:
room_request[1][1][2011-08-21]
我如何从中获取第三个片段?
我尝试了以下操作,但我不太确定我在做什么,所以很难找出我哪里出错了。
.match(/\[(.*?)\]/);
但这会返回 [1]
片段。 (我猜是第一个)。 然后,我在这里询问,人们告诉我添加一个全局标志:
.match(/\[(.*?)\]/g)[2];
在其他情况下,我使用了这个正则表达式,效果很好。但是,在这种情况下,我想要方括号内的内容。它返回:
[2011-08-21]
但我真的想要2011-08-21
。
我该怎么做?多谢。
如果有人可以推荐有关正则表达式的任何不错的资源,那就太好了。我开始了解最基本的知识,但大多数东西都太令人困惑了。谢谢。
Still completely stuck with regex's and square brackets. Hopefully someone can help me out.
Say I have a string like this:
room_request[1][1][2011-08-21]
How would I grab the third fragment out of it?
I tried the following, but I'm not exactly sure what I'm doing so it's fairly hard to figure out where I'm going wrong.
.match(/\[(.*?)\]/);
But this returns the [1]
fragment. (The first one, I guess).
So then, I asked here on SO and people told me to add a global flag:
.match(/\[(.*?)\]/g)[2];
In other cases that I've used this regex, this worked fine. However, in this case, I want the stuff INSIDE the square brackets. It returns:
[2011-08-21]
But I really want 2011-08-21
.
How can I do this? Thanks a lot.
If anyone could recommend any decent resources about regular expressions, that'd be great aswell. I'm starting to understand the very basics but most of this stuff is far too confusing atm. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两种可能的方法。要获取第三个括号表达式:
或者,如果您知道所需的表达式始终位于字符串的末尾:
Two possible methods. To grab the third bracketed expression:
Or, if you know that the expression you want is always at the end of the string:
我认为这不太混乱:
基本上,它挑选出包含某些内容的方括号的第三个匹配项。你会得到两个匹配的匹配结果 - 整个 [1][1][2011-08-21] (无论出于何种原因)和匹配的日期:2011-08-21
我的正则表达式有点生疏,但这肯定作品。
This is a little less messy I think:
Basically, it picks out the third match of the square brackets containing something. You get the match result back with two matches - the whole [1][1][2011-08-21] (for whatever reason) and the matched date: 2011-08-21
My regex is a little rusty, but this certainly works.