title: Mask phone number in R
body: <p>My raw data has a lot of personal information, so I am masking them in R. The sample data and my original code are below:</p>
  <pre><code>install.packages(&quot;stringr&quot;)
  library(string)
  
  x = c(&quot;010-1234-5678&quot;,
        &quot;John 010-8888-8888&quot;,
        &quot;Phone: 010-1111-2222&quot;,
        &quot;Peter 018.1111.3333&quot;,
        &quot;Year(2007,2019,2020)&quot;,
        &quot;Alice 01077776666&quot;)
  
  df = data.frame(
    phoneNumber = x
  )
  
  pattern1 = &quot;\\d{3}-\\d{4}-\\d{4}&quot;
  pattern2 = &quot;\\d{3}.\\d{4}.\\d{4}&quot;
  pattern3 = &quot;\\d{11}&quot;
  
  delPhoneList1 &lt;- str_match_all(df, pattern1) %&gt;% unlist
  delPhoneList2 &lt;- str_match_all(df, pattern2) %&gt;% unlist
  delPhoneList3 &lt;- str_match_all(df, pattern3) %&gt;% unlist
  </code></pre>
  <p>I found three types of patterns from the dataset and each result is below:</p>
  <pre><code>&gt; delPhoneList1
  [1] &quot;010-1234-5678&quot; &quot;010-8888-8888&quot; &quot;010-1111-2222&quot;
  &gt; delPhoneList2
  [1] &quot;010-1234-5678&quot; &quot;010-8888-8888&quot; &quot;010-1111-2222&quot; &quot;018.1111.3333&quot; &quot;007,2019,2020&quot;
  &gt; delPhoneList3
  [1] &quot;01077776666&quot;
  </code></pre>
  <p>Pattern1 is the typical type of phone number in my country using a dash, but someone types in the number like pattern2 using a comma. However, pattern2 also includes pattern1, so it detects the other pattern like a series of the year. It is an unexpected result.</p>
  <p><strong>My question is how to match the exact pattern that I define.</strong> The pattern2 includes excessive patterns such as <code>&quot;007,2019,2020&quot;</code> from <code>&quot;Year(2007,2019,2020)&quot;</code>.</p>
  <p>Additionally, the next step is masking the number using the below code:</p>
  <pre><code>for (phone in delPhoneList1) {
    df$phoneNumber &lt;- gsub(phone, &quot;010-9999-9999&quot;, df$phoneNumber)
  }
  </code></pre>
  <p>I think the code is perfect for me, but if you had a more efficient way, please let me know.</p>
  <p>Thanks.</p>