17

Using Ruby + regex, given:

[email protected]

I want to obtain just: 31313131313

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

Here's what I have so far:

to = '[email protected]'

to.split(/\+/@mysite.com.*/).first.strip
1
  • 1
    This question is incredibly similar to your other question asked two hours later. Commented Nov 19, 2010 at 0:16

4 Answers 4

37

Between 1st + and 1st @:

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

Between 1st + and last @:

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

Between last + and last @:

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

Between last + and 1st @:

to[/.*\+(.*?)@/,1]
Sign up to request clarification or add additional context in comments.

2 Comments

to[/\+(.*?)@/,1] - The number 1 is for first match found in string ?
@stack1, yes it is for what is inside the first (). Just like .match(//)[1] or .match(//).group(1) in some other languages. Usually you are retrieving the single substring when applying regex, so the ,1 is rather usual in Ruby.
6

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

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

2 Comments

this works, but its too many lines of code :) btw, where do you get questions for your codequizzes website ?
@stack1- I make up all the questions on CodeQuizzes :)
2

Here is a solution based on regex lookbehind and lookahead.

email = "[email protected]"
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

1 Comment

This is a really well-constructed answer. Thank you
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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.