CPak
CPak

Reputation: 13591

regex to capture pattern with non-fixed length lookbehind - split string

I'd like to split the string into the following

S <- "No. Ok (whatever). If you must. Please try to be careful (shakes head)."

[1] No.
[2] Ok (whatever). If you must. 
[3] Please try to be careful (shakes head).

The pattern is the first . before each (...).

I'm familiar with (?<=...) (i.e. positive lookbehind) but this doesn't seem to work with non-fixed length patterns. I'd like to know if I'm wrong about positive lookbehind or if there's some regex magic to do this. Thanks!

Upvotes: 1

Views: 103

Answers (1)

Sweeper
Sweeper

Reputation: 273265

Note that I don't know much about ruby, but there should be something like a split method that uses a regex pattern as a delimiter and split the string accordingly.

Use this regex:

(?<=\.) (?=[^.]+?\(.+?\))

This looks for a space character. Behind the space, there must be a dot (?<=\.). After it (?=, there must be a bunch of characters that are not dots [^.]+?, and then a pair of brackets with something inside \(.+?\).

Try it online: https://regex101.com/r/8PcbFJ/1

Upvotes: 2

Related Questions