简体   繁体   中英

Match strings with line breaks between two characters

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.

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM