python Regex match till word if word found else match complete string and match group will be greater then 0

Viewed 28

I am writing a regex to match string till specific word if word is in string else need to match full string. and match result should be group 1. here word is: -my-word

mylaptop-my-word > mylaptop (group1 match)

mylaptop > mylaptop (group1 match)

mylaptop-my-word-hello-my-word > mylaptop-my-word-hello (group1 match)

so far I tried this:

([\s\S]+)-my-word|([\s\S]+)

but it giving me

mylaptop-my-word > mylaptop (group1 match)

mylaptop > mylaptop (group2 match)

Need to be group1 match

1 Answers

You can use

(?s)^((?:(?!-my-word).|-my-word(?=.*-my-word))+)

See the regex demo.

Details:

  • (?s) - a re.DOTALL inline modifier flag
  • ^ - start of string
  • (?:(?!-my-word).|-my-word(?=.*-my-word))+ - one or more occurrences of:
    • (?!-my-word). - any char that is not a starting point of the -my-word char sequence
    • | - or
    • -my-word(?=.*-my-word) - -my-word that is followed with another -my-word after any zero or more chars as many as possible
Related