简体   繁体   English

ruby,使用正则表达式在两个字符串之间找到一些东西

[英]ruby, using regex to find something in between two strings

Using Ruby + regex, given: 使用Ruby + regex,给出:

starting-middle+31313131313@mysite.com

I want to obtain just: 31313131313 我想获得: 31313131313

ie, what is between starting-middle+ and mysite.com 即, starting-middle+mysite.com

Here's what I have so far: 这是我到目前为止所拥有的:

to = 'starting-middle+31313131313@mysite.com'

to.split(/\+/@mysite.com.*/).first.strip

Between 1st + and 1st @ : 在第1 +和第1 @

to[/\+(.*?)@/,1]

Between 1st + and last @ : 在第一个+和最后一个@

to[/\+(.*)@/,1]

Between last + and last @ : 在最后+和最后一个@

to[/.*\+(.*)@/,1]

Between last + and 1st @ : 在最后+和第一@

to[/.*\+(.*?)@/,1]

Here is a solution without regex (much easier for me to read): 这是一个没有正则表达式的解决方案(我更容易阅读):

i = to.index("+")
j = to.index("@")
to[i+1..j-1]

If you care about readability, i suggest to just use "split", like so: string.split("from").last.split("to").first or, in your case: 如果你关心可读性,我建议只使用“split”,如下所示:string.split(“from”)。last.split(“to”)。first或者,在你的情况下:

to.split("+").last.split("@").first to.split( “+”)。last.split( “@”)。第一

use the limit 2 if there are more occurancies of '+' or '@' to only care about the first occurancy: to.split("+",2).last.split("@",2).first 使用限制2如果有更多的'+'或'@'只关心第一次出现:to.split(“+”,2).last.split(“@”,2).first

Here is a solution based on regex lookbehind and lookahead. 这是一个基于正则表达式lookbehind和lookahead的解决方案。

email = "starting-middle+31313131313@mysite.com"
regex = /(?<=\+).*(?=@)/
regex.match(email)
=> #<MatchData "31313131313">

Explanation 说明

  1. Lookahead is indispensable if you want to match something followed by something else. 如果你想匹配其他东西,那么Lookahead是必不可少的。 In your case, it's a position followed by @, which express as (?=@) 在你的情况下,它是一个跟随@的位置,表示为(?=@)

  2. Lookbehind has the same effect, but works backwards. Lookbehind具有相同的效果,但向后工作。 It tells the regex engine to temporarily step backwards in the string, to check if the text inside the lookbehind can be matched there. 它告诉正则表达式引擎暂时在字符串中向后退一步,以检查lookbehind内的文本是否可以在那里匹配。 In your case, it's a position after + , which express as (?<=\\+) 在你的情况下,它是+之后的一个位置,表示为(?<=\\+)

so we can combine those two conditions together. 所以我们可以将这两个条件结合起来。

lookbehind   (what you want)   lookahead
    ↓              ↓             ↓
 (?<=\+)           .*          (?=@)

Reference 参考

Regex: Lookahead and Lookbehind Zero-Length Assertions 正则表达式:Lookahead和Lookbehind Zero-Length断言

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM