-1

The question was a regex that does not contain the letters PART. Here was an answer: /^((?!PART).)*$/

Link to question: How to match a line not containing a word

My question is, why does it not work unless you indicate start(^) and end($)? Why doesn't only ((?!PART).)* work?

  • The question you link to answers your question: "The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART." – Jack Jun 16 '17 at 01:31

2 Answers2

0

The pattern

/^((?!PART).)*$/

matches the general pattern ^.*$, namely anything occurring in between the start and end anchors. However, it also contains a negative assertion (?!PART). As written, your pattern asserts that, at each position in the string, the string PART does not appear when looking forward for four characters.

If you just use this pattern:

/((?!PART).)*/

then it only means that PART does not occur at any certain point in the string. But as this demo shows, a string such as PART hello world would match this alternative pattern, and may not be what you want.

Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
0

Because the concept of "line" means nothing without the "multiline" flag re.M. Also if you only match the part of the line containing PART then all of your matches will also be the string "PART" or in the example above "PART" + the entire remaining line (depending on flags).

^ = start of line $ = end of line re.S = DOTALL, a dot includes whitespace/end of line markers re.M = MULTILINE do not treat lineendings as match end

Without making that explicit you are only doing a substring matching and ignoring line endings entirely.

SpliFF
  • 35,724
  • 15
  • 80
  • 113