Matlab: Regular expression: Except: Requires dot '.' at end to function

Viewed 34

Why does the following regular expression to find all instances EXCEPT abd require a dot at the end of the given pattern to function as intended:

>> regexp({'abc';'abd'},'^(?!abd$)')
ans =
{
  [1,1] = [](1x0)
  [2,1] = [](1x0)
}

>> regexp({'abc';'abd'},'^(?!abd$).')
ans =
{
  [1,1] = 1
  [2,1] = [](1x0)
}

This applies in the simpler case without use of a cell as well:

>> regexp('abc','^(?!abd$)')
ans = [](1x0)

>> regexp('abc','^(?!abd$).')
ans = 1
1 Answers

This is clear after you check the regexp reference page and see that by default, empty matches are not returned.

Note that ^(?!abd$) pattern is a sequence of two non-consuming patterns, a start of string anchor (^) and a negative lookahead ((?!abd$)) that matches a location in a string that is not immediately followed with abd and end of string.

When you add a . after the lookahead, you introduce a consuming part to the regex, and now it actually matches and consumes any single char, and then the regexp returns a non-empty match.

All you need is to override the default behavior by adding the emptymatch option:

>> regexp({'abc';'abd'},'^(?!abd$)', 'emptymatch'
)
ans =
{
  [1,1] =  1
  [2,1] = [](1x0)
}
Related