Regular expression finding '\n'
<p>I'm in the process of making a program to pattern match phone numbers in text.</p>

<p>I'm loading this text:</p>

<pre><code>(01111-222222)fdf
01111222222
(01111)222222
01111 222222
01111.222222
</code></pre>

<p>Into a variable, and using "findall" it's returning this:</p>

<pre><code>('(01111-222222)', '(01111', '-', '222222)')
('\n011112', '', '\n', '011112')
('(01111)222222', '(01111)', '', '222222')
('01111 222222', '01111', ' ', '222222')
('01111.222222', '01111', '.', '222222')
</code></pre>

<p>This is my expression:</p>

<pre><code>ex = re.compile(r"""(
    (\(?0\d{4}\)?)?       # Area code
    (\s*\-*\.*)?          # seperator
    (\(?\d{6}\)?)        # Local number
     )""", re.VERBOSE)
</code></pre>

<p>I don't understand why the '\n' is being caught. </p>

<p>If <code>*</code> in '<code>\\.*</code>' is substituted for by '<code>+</code>', the expression works as I want it. Or if I simply remove <code>*</code>(and being happy to find the two sets of numbers separated by only a single period), the expression works.</p>

<p>The <code>\s</code> matches both <em>horizontal</em> and <em>veritcal</em> whitespace symbols. If you have a <code>re.VERBOSE</code>, you can match a normal space with an escaped space <code>\ </code>. Or, you may exclude <code>\r</code> and <code>\n</code> from <code>\s</code> with <code>[^\S\r\n]</code> to match horizontal whitespace.</p>

<p>Use</p>

<pre><code>ex = re.compile(r"""(
    (\(?0\d{4}\)?)?       # Area code
    ([^\S\r\n]*-*\.*)?   # seperator   ((HERE))
    (\(?\d{6}\)?)        # Local number
     )""", re.VERBOSE)
</code></pre>

<p>See the <a href="https://regex101.com/r/TefKkm/3" rel="nofollow">regex demo</a></p>

<p>Also, the <code>-</code> outside a character class does not require escaping.</p>

python regex