1

I'm trying to figure out the right regex to get the output as expected. It's a part of a bigger problem, and I'm stuck right here. I only want the array elements with the dot(.) notation in them and in the second part after the dot, if there is a symbol (@) group that separately as well.

(Input) arr = ["ab", "cd.ef", "gh.ij@kl"]

(Expecting) [["cd", "ef"], ["gh", "ij", "kl"]]

I have tried the following regex's to achieve this:

arr.join(",").scan(/(\w+)\.(\w+)@?(\w+)/) gives me [["cd", "e", "f"], ["gh", "ij", "kl"]]

Also, tried this:

arr.join(",").scan(/(\w+)\.(\w+)@(\w+)/) gives me ["gh", "ij", "kl"]]

Could someone please provide some guidance on how to get the expected outcome?

2
  • 1
    right now /(\w+)\.(\w+)@?(\w+)/ is causing it to capture the "f" separately so that it matches the pattern if you make that last capture group optional /(\w+)\.(\w+)@?(\w+)?/ you will get [["cd", "ef", ""], ["gh", "ij", "kl"]] Commented May 20, 2020 at 17:31
  • makes sense, making the part after @ optional is giving me the output i expect. thanks Commented May 20, 2020 at 17:46

1 Answer 1

2

I'd break it into two steps. First, you can grep all elements with a "." character, then map each to a split version of itself using your two delimiters:

arr = ["ab", "cd.ef", "gh.ij@kl"]
arr.grep(/\./).map{|e| e.split(/[@.]/)} # => [["cd", "ef"], ["gh", "ij", "kl"]]

If you need to be sure that @ is permitted in the first section of the split, you could try something like

arr = ["[email protected]@garply"]
pat = /([^.]+)\.([^@]+)(?:@(.+))?/
arr.grep(/\./).map{|e| e.scan(pat).flatten.compact} # => [["foo@bar", "baz", "garply"]]
Sign up to request clarification or add additional context in comments.

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.