Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match everything up to first period

Tags:

regex

ruby

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?

like image 988
Yarin Avatar asked Jun 01 '17 17:06

Yarin


2 Answers

/^([^.]+)/

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.

like image 53
Matthew Brock Carey Avatar answered Nov 06 '22 11:11

Matthew Brock Carey


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."
like image 37
Casimir et Hippolyte Avatar answered Nov 06 '22 09:11

Casimir et Hippolyte