'Using Regex how to extract a string until a character only if present, else till end [closed]

I am trying to extract string using Regex in python, that starts with word 'swap' till first '/' if present, or till end

For example:

str1: 'abcd/swap 12345 ijkl/mnop/tyuio'
str2: 'abcd/swap ijkl 1234'
str3: 'swap ijklm nop'

Required Output:

from str1: 'swap 12345 ijkl'
from str2: 'swap ijkl 1234'
from str3: 'swap ijklm nop'

I am new to regex and tried many combinations but cant get all 3 situations.



Solution 1:[1]

An efficient ways to do this is

r"swap.*?(?:/|$)"

https://regex101.com/r/ght9hu/1

or r"swap.*?(?=/|$)" with no match of the ender.

https://regex101.com/r/VSX1hp/1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sln