title: How to improve performance for masking method with credit card regex in java
body: <p>i have this function to identify credit card by regex in input string and mask it without the last 4 digits:</p>
  <pre><code>public CharSequence obfuscate(CharSequence data) {
      String[] result = data.toString().replaceAll(&quot;[^a-zA-Z0-9-_*]&quot;, &quot; &quot;).trim().replaceAll(&quot; +&quot;, &quot; &quot;).split(&quot; &quot;);
      for(String str : result){
          String originalString = str;
          String cleanString = str.replaceAll(&quot;[-_]&quot;,&quot;&quot;);
          CardType cardType = CardType.detect(cleanString);
          if(!CardType.UNKNOWN.equals(cardType)){
              String maskedReplacement = maskWithoutLast4Digits(cleanString ,replacement);
              data = data.toString().replace(originalString , maskedReplacement);
          }
      }
      return data;
  }
  
  static String maskWithoutLast4Digits(String input , String replacement) {
      if(input.length() &lt; 4){
          return input;
      }
      return input.replaceAll(&quot;.(?=.{4})&quot;, replacement);
  }
  </code></pre>
  <p>//pattern enum</p>
  <pre><code> public enum CardType {
  UNKNOWN,
  VISA(&quot;^4[0-9]{12}(?:[0-9]{3}){0,2}$&quot;),
  MASTERCARD(&quot;^(?:5[1-5]|2(?!2([01]|20)|7(2[1-9]|3))[2-7])\\d{14}$&quot;),
  AMERICAN_EXPRESS(&quot;^3[47][0-9]{13}$&quot;),
  DINERS_CLUB(&quot;^3(?:0[0-5]|[68][0-9])[0-9]{11}$&quot;),
  DISCOVER(&quot;^6(?:011|[45][0-9]{2})[0-9]{12}$&quot;);
  
  private Pattern pattern;
  
  CardType() {
      this.pattern = null;
  }
  
  CardType(String pattern) {
      this.pattern = Pattern.compile(pattern);
  }
  
  public static CardType detect(String cardNumber) {
  
      for (CardType cardType : CardType.values()) {
          if (null == cardType.pattern) continue;
          if (cardType.pattern.matcher(cardNumber).matches()) return cardType;
      }
  
      return UNKNOWN;
  }
  
  
  public Pattern getPattern() {
      return pattern;
  }
  }
  </code></pre>
  <p>input1:
  &quot;Valid American Express card: 371449635398431&quot;.</p>
  <p>output1:
  &quot;Valid American Express card: ***********8431&quot;</p>
  <p>input2:
  &quot;Invalid credit card: 1234222222222&quot; //not mach any credit card pattern</p>
  <p>output2:
  &quot;Invalid credit card: 1234222222222&quot;</p>
  <p>input3:
  &quot;Valid American Express card with garbage characters: &lt;3714-4963-5398-431&gt;&quot;</p>
  <p>output:
  &quot;Valid American Express card with garbage characters: &lt;***********8431&gt;&quot;</p>
  <p>this is not the best way to to do the masking since this method will be called for each tag in huge html and each line in huge text files
  how i can improve the performance of this method</p>