[JAVA] replaceFirst을 개선한 replaceOne

[JAVA] replaceFirst을 개선한 replaceOne

 

자바 String에는 기존에 replace, replaceFirst라는 메서드가 존재한다.

replace는 바꾸고 싶은 값이 n개 있으면 n개가 전부 바뀐다. 딱 하나만 바꿀 때 쓰는 메서드가 replaceFirst다.

그런데 replaceFirst는 파라미터에 정규식을 넣게 되어 있기 때문에, 스트링을 무심코 쓰다 보면 잘못 바뀐다.

특히 소괄호를 한 개만 쓰면 값이 정상적으로 바뀌지 않고 에러가 나는 경우가 있다.

소괄호나 마침표 같은 특수문자 앞에 역슬래시를 2개를 붙이는 방법도 있지만 정규식을 쓰지 않는 메서드를 만드는게 더 편하다고 생각했다.

 

새로 만든 메서드는 아래와 같다. 정규식이 통하지 않는 replaceOne 이다.

    public String replaceOne(String fullStr, String oldStr, String newStr) {
        StringBuffer res = new StringBuffer();
        try {
            if (fullStr == null || fullStr.length() == 0) {
                return fullStr;
            }

            if (oldStr == null || oldStr.length() == 0) {
                return fullStr;
            }

            if (newStr == null || newStr.length() == 0) {
                return fullStr;
            }

            int posOldStr = fullStr.indexOf(oldStr);

            if (posOldStr >= 0) {
                res.append(fullStr.substring(0, posOldStr));
                res.append(newStr);
                res.append(fullStr.substring(posOldStr + oldStr.length()));
            } else {
                return fullStr;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return fullStr;
        }

        if (res == null || res.length() == 0) {
            return fullStr;
        }

        return res.toString();
    }