Search code examples
pythonregexpython-re

Finding a 'part' word with RegEx


I want to find chapter and find words in a sentence.

sentence1 = 'chapter1'
sentence2 = 'chapter 1'
sentence3 = 'part1'
sentence4 = 'part 1'
sentence5 = 'party'

re.search('((\bchapter\b|\bpart$\b)|[ ^a-z*,0-9]+)+', sentence5)

But I don't want to get some words like 'part(y)'. I mean code should find first 4 sentences but 5th sentence shouldn't be find.


Solution

  • $ is end of line, not word boundary.

    ^((\bchapter)|(\bpart))\s?[0-9]