Split line by character separator and subelements

Viewed 42

In this string:

#animal the cat   #tree palm tree

I want to match

#animal  
the cat

and

#tree  
palm tree

I have found several ways to match the first one but I have problems stopping at the second # character and continue from there.

(?<=#)(\w*)\s(.*)(?!#)

finds only one match capturing everything after #animal until the end.

Lazyfiying the capturer next to the tag captures the tags

(?<=#)(\w*)\s(.*?)(?!#)

What am I missing?

1 Answers

You need

(#\w+)\s+(.*?)(?=#\w|$)

See the regex demo.

If there can be line breaks, you may replace . with [\s\S] / [\w\W] / [\d\D] / (?s:.*?) or just prepend the pattern with (?s).

Details:

  • (#\w+) - Group 1: a # char and then one or more word chars
  • \s+ - one or more whitespaces
  • (.*?) - Group 2: any zero or more chars other than line break chars as few as possible
  • (?=#\w|$) - immediately to the right, there must be # and one or more word chars or end of string.
Related