如何让正则表达式忽略 URL 字符串?
我有以下正则表达式,通过用分号分隔字符串来创建值的哈希值:
Hash["photo:chase jarvis".scan(/(.*)\:(.*)/)]
// {'photo' => 'chase jarvis'}
但我也希望能够在字符串中包含 URL 并识别它,以便它在哈希值一侧维护 URL 部分,即:
Hash["photo:http://www.chasejarvis.com".scan(/(.*)\:(.*)/)]
// Results in {'photo:http' => '//www.chasejarvis.com'}
我当然想要:
Hash["photo:chase jarvis".scan(/ ... /)]
// {'photo' => 'http://www.chasejarvis.com'}
I have the following Regexp to create a hash of values by separating a string at a semicolon:
Hash["photo:chase jarvis".scan(/(.*)\:(.*)/)]
// {'photo' => 'chase jarvis'}
But I also want to be able to have URL's in the string and recognize it so it maintains the URL part in the value side of the hash i.e:
Hash["photo:http://www.chasejarvis.com".scan(/(.*)\:(.*)/)]
// Results in {'photo:http' => '//www.chasejarvis.com'}
I want, of course:
Hash["photo:chase jarvis".scan(/ ... /)]
// {'photo' => 'http://www.chasejarvis.com'}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只想匹配第一个冒号,可以将
(.*)\:(.*)
更改为([^:]*)\:(.*)
。或者,您可以使其成为非贪婪匹配,但我更喜欢说“不是冒号”。
If you only want to match up to first colon you could change
(.*)\:(.*)
to([^:]*)\:(.*)
.Alternatively, you could make it a non-greedy match, but I prefer saying "not colon".
如何查出一个人的姓氏和名字?
将
chasejarvis
更改为chase
和jarvis
可能无法实现,除非您有解决方案。您已经知道项目中每个人的名字了吗?没有人拥有像
charvisdjarvis
这样的中间名首字母(假设名字是“Charvis D. Jarvis”。)?How do figure out a person's family name and first name?
Changing
chasejarvis
tochase
andjarvis
might not be possible unless you have a solution for that.Do you already know everyone's name in your project? Nobody is having the initial of a middle name like
charvisdjarvis
(assuming the name is "Charvis D. Jarvis".)?