Language/Java

[Regular Expression] 문자열 중 숫자분리

아르비스 2011. 9. 28. 08:58
문자열중 숫자만 분리해서 그 값을 증가시키는 메소드가 필요하여 정리함.

Pattern을 이용하여 문자열 중 pattern값을 인식하는 방식

Method

 public String findNextStr(String input) throws IOException

    {

        String nextStr = null;

        Pattern pattern = Pattern.compile("([a-z]+)+([0-9]+)");

        Matcher pStartMatcher = pattern.matcher(input.toLowerCase());

        while (pStartMatcher.find())

        {

            String strFull = pStartMatcher.group(0);

            String strPart1 = pStartMatcher.group(1);

            String strPart2 = pStartMatcher.group(2);

            

            System.out.println(strFull);

            System.out.println(strPart1);

            System.out.println(strPart2);

            

            nextStr = strPart1 + String.valueOf((Integer.valueOf(strPart2)+1));

        }

        return nextStr;

    }

 
method 호출

    public static void main(String[] args) throws IOException

    {

        ControllerMethod ctrl = new ControllerMethod();

        

        String table = "AbcdefGHijk10002ADc";

        String nextStr = null;

        

        nextStr = ctrl.findNextStr(table);

        

        System.out.println(nextStr);

    }

 
실행결과 

abcdefghijk10002

abcdefghijk

10002

abcdefghijk10003

 
코드는 쉬운데.. 개념을 처음 접하기엔 어렵네.ㅋㅋ