Examples using boundary constructs

Which regex should be used to match "at" when the input is 'Hat at work"?

    batb

The preceding regex should be used because  (word boundary) stops the regex engine to match at in Hat, because at can match full words only.

What should be regex if we only want to match at in Hat but not the one that was matched in the preceding regex?

    Bat

Now, this regex will match at that is a part of Hat because B asserts a position that is between two word characters or a position between two non-word characters. Because of the presence of B in the regex, it matches at only in Hat but not the word at.

If the input is suppress expression press depression, what will be the matches if the regex is BpressB?

    suppress expression press depression

This is because B matches the position between word characters, and the other instances, suppress and press, have non-word characters after press.

If the input is ppp 555 , then show the matched text using the following two regular expressions:

  • Ap+ 5{3}
  • Ap+ 5{3}z

Here are the matches:

A) ppp
555
B) No match

The starting part, Ap+ 5{3}, is common in both the regex patterns and matches ppp 555 both the times. However, we are getting no match in the second case because of the subtle difference between the  and z assertions.  asserts the position at the end or just before the last line terminator whereas z always asserts the position at the very end. Due to the presence of at the end of the file, our second regex does not match. If we change the second regex to Ap+ 5{3} z, then it will match the entire input.

Note that the end anchor $ also behaves like  if the MULTILINE flag (will be discussed later) is not enabled in an input text with multiple lines. Thus, the preceding input string can also be matched using ^p+ 5{3}$.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.226.83