Ben
Ben

Reputation: 55

How do you stop `scan` after the first match of regular expression?

I have:

bigtext = "I am happy. We are happy. He is happy too." 

I want to scan the text and stop at the first occurrence of the word "happy".

I tried this:

bigtext.scan(/happy?/) 

I used ? to stop, but it continues to scan, and returns three occurrences of "happy".

Upvotes: 1

Views: 293

Answers (4)

sawa
sawa

Reputation: 168199

Use a block with scan, and place break after you have done whatever to be done within the block.

Without break:

bigtext.scan(/happy/) do
  p $`                                                                            #`
end
# >> "I am "
# >> "I am happy. We are "
# >> "I am happy. We are happy. He is "

With break:

bigtext.scan(/happy/) do
  p $`                                                                            #`
  break
end
# >> "I am "

Upvotes: 0

vks
vks

Reputation: 67978

^.*?happy

You can use this m or multiline mode.See demo.

https://regex101.com/r/oF9hR9/12

Upvotes: 1

Martin Konecny
Martin Konecny

Reputation: 59651

What exactly are you trying to achieve? If you want to know whether the string contains the word "happy", why not just use

find = "happy"
if bigtext.include?(find)
  return [find]

Otherwise you could use match if you need a regex operation to return an array

bigtext.match(/happy/).to_a #  returns ["happy"]

Upvotes: 0

Amadan
Amadan

Reputation: 198418

/happy?/ will match "happ" or "happy"; you are misusing the ? (optional match) operator.

What you want is not scan (get all occurences), but match or =~ or even [].

bigtext =~ /happy/
# => 5
bigtext.match(/happy/)
# => #<MatchData "happy"> 
bigtext[/happy/]
# => "happy"

Upvotes: 0

Related Questions