2

How can I match line breaks between two asterisks in Ruby? I have this string

Foo **bar**
test **hello
world** 12345

and I only want to find

**hello
world**

I tried it with \*{1,2}(.*)\n(.*)\*{1,2} but this matches

**bar**
test **

I played with a non greedy matcher like \*{1,2}(.*?)\n(.*?)\*{1,2} but this doesn't work either, so I hope someone can help.

23tux
  • 14,104
  • 15
  • 88
  • 187
  • 2
    Try [`/\*{1,2}\b([^*]*)\R([^*]*)\b\*{1,2}/`](http://rubular.com/r/o3tfM0pWpV). – Wiktor Stribiżew Aug 16 '18 at 14:15
  • thanks this works! – 23tux Aug 16 '18 at 14:16
  • Do you with to match strings that begin and end with a pair of asterisks and contain a line break? If so, are there any restrictions on the characters between the pairs of asterisks other than the line break? For example, must they be word characters, or are other characters permitted, including or excluding other line breaks? Can the line break(s) be adjacent to the beginning or ending pairs of asterisks? – Cary Swoveland Aug 16 '18 at 19:12

2 Answers2

2

You may use

/\*{1,2}\b([^*]*)\R([^*]*)\b\*{1,2}/

See the Rubular demo

Details

  • \*{1,2} - 1 or 2 asterisks
  • \b - a word boundary, the next char must be a word char
  • ([^*]*) - Group 1: any 0+ chars other than *
  • \R - a line break sequence
  • ([^*]*) - Group 2: any 0+ chars other than *
  • \b - a word boundary, the preceding char must be a word char
  • \*{1,2} - 1 or 2 asterisks
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
-1

Wiktor already gave a good answer. Here is another way of doing it:

(?<=\*{1,2})([^*])*(?=\*{1,2})

Tested here

NOTE: This will not work in Ruby, but it can work in some other languages

From the link in this answer:

Subexp of look-behind must be fixed-width.

No Name
  • 612
  • 6
  • 15
  • @CarySwoveland Thanks for the note. I was debating whether I should leave this answer since it doesn't work in Ruby. It might help someone who needs something similar in JavaScript, for example. – No Name Aug 16 '18 at 17:44