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
4

2 に答える 2

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"]

または:

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"]
于 2013-09-15T17:30:27.160 に答える