Finding a string between two ranges of strings or end of string

Viewed 237

I am trying to extract whatever is between two strings. The first string is a known string, the second string could be from a list of strings.

For example,

We have the start string and the end strings. We want to get the text between these.

start = "start"
end = ["then", "stop", "other"]

Criteria

test = "start a task then do something else"
result = "a task"

test = "start a task stop doing something else"
result = "a task"

test = "start a task then stop"
result = "a task" 

test = "start a task"
result = "a task"

I have looked at using a regex, and I got one which works for between two strings, I just cannot create one which words with a option of strings: (?<=start\s).*(?=\sthen)

I have tried using this: (?<=start\s).*(?=\sthen|\sstop|\sother) but this will include 'then, stop or other' in the match like so: "start a task then stop" will return "a task then"

I have also tried to do a 'match any character except the end list" in the capture group like so: (?<=start\s)((?!then|stop|other).*)(?=\sthen|\sstop|\sother) but this has the same effect as the one above.

I am using swift, so I am also wondering whether this can be achieved by finding the substring between two strings.

Thanks for any help!

1 Answers

You may use

(?<=start\s).*?(?=\s+(?:then|stop|other)|$)

See the regex demo. To search for whole words, add \b word boundary in proper places:

(?<=\bstart\s).*?(?=\s+(?:then|stop|other)\b|$)

See another regex demo

Details

  • (?<=start\s) - a positive lookbehind that matches a location immediately preceded with start string and a whitespace
  • .*? - any 0+ chars other than line break chars, as few as possible
  • (?=\s+(?:then|stop|other)|$) - a position in the string that is immediately followed with
    • \s+ - 1+ whitespaces
    • (?:then|stop|other) - one of the words
    • |$ - or end of string.
Related