EN VI

Java - Convert a regex match repaceAll() to replace() for sonar rule?

2024-03-12 04:00:06
How to Java - Convert a regex match repaceAll() to replace() for sonar rule

I have a Java String that is converted to ssn format via input.replaceAll("(\\d{3})(\\d{2})(\\d{4})","$1-$2-$3") which is flagged by sonar rule as described in title. Just substituting the replace does not work, so I'm looking for a solution here.

Solution:

You can do it by using precompiled Pattern and Matcher, or by substring without regex.

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Main {
    public static void main(String[] args) {
        String input = "123456789";

        // Approach 1: Using precompiled Pattern and Matcher
        Pattern pattern = Pattern.compile("(\\d{3})(\\d{2})(\\d{4})");
        Matcher matcher = pattern.matcher(input);
        String ssnFormattedPattern = matcher.replaceAll("$1-$2-$3");
        System.out.println("Using Pattern and Matcher: " + ssnFormattedPattern);

        // Approach 2: Using substring without regex
        String ssnFormattedSubstring = input.substring(0, 3) + "-" + input.substring(3, 5) + "-" + input.substring(5);
        System.out.println("Using substring: " + ssnFormattedSubstring);
    }
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login