ruby, using regex to find something in between two strings

亡梦爱人 提交于 2021-02-06 01:56:05

问题


Using Ruby + regex, given:

starting-middle+31313131313@mysite.com

I want to obtain just: 31313131313

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

Here's what I have so far:

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

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

回答1:


Between 1st + and 1st @:

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

Between 1st + and last @:

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

Between last + and last @:

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

Between last + and 1st @:

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



回答2:


Here is a solution without regex (much easier for me to read):

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



回答3:


If you care about readability, i suggest to just use "split", like so: string.split("from").last.split("to").first or, in your case:

to.split("+").last.split("@").first

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




回答4:


Here is a solution based on regex lookbehind and 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. In your case, it's a position followed by @, which express as (?=@)

  2. Lookbehind has the same effect, but works backwards. It tells the regex engine to temporarily step backwards in the string, to check if the text inside the lookbehind can be matched there. 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



来源:https://stackoverflow.com/questions/4218986/ruby-using-regex-to-find-something-in-between-two-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!