4

I see couple of questions on multiple regex patterns in different contexts but I am unable to get a grip on it.

I have a string str = "Hello, how are you. Hello, I am lloyds" in which I would like to apply multiple patterns to extract all Hellos and all lls in one go to get ["Hello", "Hello", "ll", "ll", "ll"]. How do I do it?

The only way I was able to do is (which is not multiple patterns in one go)

str = "Hello, how are you. Hello, I am lloyds"
a = []
a << str.scan(/Hello/)
a << str.scan(/ll/)
a.flatten
1
  • 2
    What you have is better written as str.scan(/Hello/) + str.scan(/ll/). And, honestly, I think separate regexes is likely to be clearer than any other complicated single one. Commented Sep 15, 2013 at 16:14

2 Answers 2

8

Because "ll" is inside "Hello", logic to include both in same scan method call requires a slightly clumsy-looking expression that double-captures the "ll". This seems close, but note the sequence interleaves "Hello" and "ll", unlike the expected output. However, as far as I can see, that would be a necessity for any regular expression that makes a single pass through the string:

str = "Hello, how are you. Hello, I am lloyds"
a = str.scan( /(He(ll)o|ll)/ ).flatten.compact
 => ["Hello", "ll", "Hello", "ll", "ll"]

The compact is necessary, because a lone "ll" will not match the inner capture, and the array may contain unwanted nils.

Sign up to request clarification or add additional context in comments.

Comments

1
str = "Hello, how the hello are you. Hello, I am lloyds"
results = []

str.scan(/hello|ll/xmi) do |match|
  target = match.downcase
  results.unshift match if target == 'hello'
  results << 'll'
end

p results

--output:--
["Hello", "hello", "Hello", "ll", "ll", "ll", "ll"]

Or:

str = "Hello, how the hello are you. Hello, I am lloyds"
hello_count = 0
ll_count = 0

str.scan(/Hello|ll/xm) do |match|
  hello_count += 1 if match == 'Hello'
  ll_count += 1 
end

results = ["Hello"] * hello_count + ["ll"] * ll_count 
p results

--output:--
["Hello", "Hello", "ll", "ll", "ll", "ll"]

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.