title: Regular Expression to mask given number either from begining or end
body: <p>I have a scenario where have to mask two number in return from my application based on the configured regular expression patterns. I have following two numbers and need to mask as shown below.</p>
  
  <ul>
  <li>20128569  -->  2012****</li>
  <li>40953186  -->  ****3186</li>
  </ul>
  
  <p>I need two regular expression patterns to achieve this pattern accordingly using the String.replaceAll(...) or some other possible way.</p>
  
  <pre><code>public static void main(String[] args) {
      String value = "20128569";
      String pattern = "(?&lt;=.{4}).?" ;
  
      String formattedValue = value.replaceAll(pattern, "*");
      System.out.println(formattedValue);
  }
  </code></pre>
  
  <p><strong>Note:</strong> I need two regular expression patterns in order to mask number as shown above. </p>
  
  <p>However currently i have resolve this issue temporally through the following code. But it is nice if i can resolve this issue through only regular expression.</p>
  
  <pre><code>        String maskedAccountNumber = Pattern.compile(aRegexPattern).matcher(aKey).replaceFirst(MASK_CHARACTER);
  
          StringBuilder maskBuffer = new StringBuilder();
          for(int i = 0; i &lt;= aKey.length() - maskedAccountNumber.length() ; i++){
                maskBuffer.append(MASK_CHARACTER);
          }
          return      maskedAccountNumber.replace(MASK_CHARACTER, maskBuffer.toString());
  </code></pre>
  
  <p>Below are the two regulare expressions i used so far:</p>
  
  <ol>
  <li>^.\d{1,3}</li>
  <li>.\d{1,3}$</li>
  </ol>