Reputation: 183499
Trying to get a lazy regex match of everything up until the first period of a sentence.
e.g. Just want to get "jack and jill." from this sentence:
"jack and jill. went up the hill. to fetch a pail."
/.+\./
matches the whole sentence (example)
/(.+?\.)/
matches each instance (example)
Is there a way to just match the first instance?
Upvotes: 11
Views: 37738
Reputation: 586
/^([^.]+)/
Let's break it down,
^
is the newline anchor
[^.]
this matches any character that's not a period
\+
to take until a period
And the expression is encapsulated with () to capture it.
Upvotes: 32
Reputation: 110675
I would be inclined to use a regex, but there are other options.
str = "jack and jill. went up the hill. supposedly to fetch a pail of water."
str[0..i] if i = str.index('.')
#=> "jack and jill."
str = "three blind mice"
str[0..i] if i = str.index('.')
#=> nil
Upvotes: 1
Reputation: 89547
If you only want the first occurrence, do not choose the scan
method that returns all results in the string. You can use the match method that returns a MatchData instance, but you can also simply write:
> "jack and jill. went up the hill. to fetch a pail."[/.+?\./]
=> "jack and jill."
Upvotes: 2