使用Ruby + regex,给定:
starting-middle+31313131313@mysite.com
我只想获取:31313131313
也就是说,starting-middle+
和mysite.com
之间有什么关系
这是我到目前为止所知道的:
to = 'starting-middle+31313131313@mysite.com'
to.split(/\+/@mysite.com.*/).first.strip
发布于 2010-11-18 20:06:28
在第1个+
和第1个@
之间
to[/\+(.*?)@/,1]
在第一个+
和最后一个@
之间
to[/\+(.*)@/,1]
在last +
和last @
之间
to[/.*\+(.*)@/,1]
在最后一个+
和第一个@
之间
to[/.*\+(.*?)@/,1]
发布于 2014-02-11 20:20:11
这是一个没有正则表达式的解决方案(对我来说更容易阅读):
i = to.index("+")
j = to.index("@")
to[i+1..j-1]
发布于 2018-10-31 23:54:37
如果你关心可读性,我建议只使用"split",就像这样: string.split("from").last.split(" to ").first或者,在你的例子中:
to.split("+").last.split("@").first
如果'+‘或'@’出现次数较多,则使用限制2,以便只关心第一次出现的情况: to.split("+",2).last.split("@",2).first
https://stackoverflow.com/questions/4218986
复制相似问题