python - regex: Matching parts of a string when the string contains part of a regex pattern -


I want to reduce the number of patterns to write using a Regex which selects any or all patterns It appears in a string.

Is it possible with Regex?

  The example pattern is: "The cat sat on the mat" I would like the pattern to match on the following string: "" "cat" "cat" ... "Cat sat on the mat " 

But it should not match the following string because it matches some words, they are divided by a non-matching word:" dog sitting "

this:

  (cat (on mat))?)?)?)?) ?)?  

Will answer your question "Remove the alternate group" legs "(...)?" For those parts which are not optional, add additional groups for those things that should be met together.

  // complete match cat cat // complete match cat sat // full match cat sat on / sat on full match cat sitting on mat / sat on full mat sitting cat / full match dog On matte / two partial matches ("the")  

To prevent the expression from matching the second "the" in the previous row, you want to add some pre-condition, such as The beginning of the line anchor:

  ^ the (cat (sat (on mat)?)?)?)?)?)?  Edit:  If you add a post-condition, mailing like an end-of-line anchor will be completely stopped at the last example, that is, the final example will not match exactly:  
  the (cat (sat (mat))?)?)?)?)?)? $  

Thanks for visiting the credit card!

There may be a post-condition that you expect to follow the match.

Alternatively, you remove the last question mark:

  the (cat (sat) (?)?)?)?)?)  

Be aware though: this will create a single "non" match, so the first line also does not match.


Comments