Stream: helpdesk (published)

Topic: ✔ How to find regex matches and splice line break?


view this post on Zulip Júlio Hoffimann (Nov 15 2025 at 01:55):

Say I have a string like

"F1 .... F2 ..... F3 ....... F10"

where the ... represent arbitrary text in between the markers FN.

I want to find all indices that satisfy the regex r"F\d+" and splice a \n so that the final result looks like

"""
F1 ...
F2 ...
F3 ...
.
.
.
F10 ...
"""

I could find the index of each regex match with m.offset for m in eachmatch(regex, text) but I wonder if there is a more straightforward method to split the text and join the sentences with \n in one go.

view this post on Zulip Júlio Hoffimann (Nov 15 2025 at 01:58):

Also found eachsplit(text, regex) but it discards the markers FN from the substrings.

view this post on Zulip Júlio Hoffimann (Nov 15 2025 at 02:17):

Current solution:

  lines = eachsplit(text, r"F\d+")
  valid = collect(lines)[begin+1:end-1]
  join(("F$i" * l for (i, l) in enumerate(valid)), "\n")

view this post on Zulip Notification Bot (Nov 15 2025 at 02:39):

Júlio Hoffimann has marked this topic as resolved.

view this post on Zulip Gunnar Farnebäck (Nov 15 2025 at 09:35):

Maybe lstrip(replace(s, r"(F\d+)" => s"\n\1")).


Last updated: Nov 27 2025 at 04:44 UTC