Reputation: 565
I have a regex to grab everything between "*"
:
str = "Donec sed odio dui. *Nullam id dolor id nibh ultricies vehicula ut*"
str.match(/\*(.*)\*/)[1]
I want the match to be able to include newline characters. How can I do it?
Upvotes: 10
Views: 6157
Reputation: 15000
You'll want to use the m
option which allows the dot to match new lines:
Donec sed odio dui. *Nullam id dolor id
nibh ultricies vehicula ut*
regex str.match(/\*(.*)\*/m)[1]
Live example: http://www.rubular.com/r/11u9TreEOL
Your expression will capture the text between the first and last *
symbol, but if you want to capture all text between each set of *
then you'd want to make the .*
less greedy like
str.match(/\*(.*?)\*/m)[1]
Live example http://www.rubular.com/r/rBLOnwy3By
Or you could tell it to simply match all non *
characters like, note the m
option is not needed as a new line character would be matched by a the negated [^*]
character class:
str.match(/\*([^*]*)\*/)[1]
Live example http://www.rubular.com/r/dhQzZ58ZzM
Upvotes: 18
Reputation: 168081
Put the m
modifier after the regex like /\*(.*)\*/m
.
By the way, your regex can be improved to:
str[/(?<=\*).*(?=\*)/m]
Upvotes: 4