Java

[Java] 정규표현식 Pattern, Matcher

Jane Kwon 2021. 2. 10. 15:17
반응형

 

정규표현식(Regular Expression)이란, 컴퓨터 과학의 정규언어로부터 유래한 것으로
특정한 규칙을 가진 문자열의 집합을 표현하기 위해 쓰이는 형식언어로,
개발을 하다보면 전화번호, 주민등록번호, 이메일 등과 같이 정해져있는 형식이 있고
사용자가 그 형식대로 제대로 입력했는지 검증을 해야하는 경우가 종종 있는데,
이런 입력값을 정해진 형식에 맞는지 검증해야 할 때 정규표현식을 사용하면 쉽게 구현이 가능하다.

 

 

 

backoffice api 에서 AWS IoT 리소스 ARN 에서
리소스의 id 와 버전 id 를 꺼내서 사용해야하는 경우가 있는데
이 때 두 가지 방법을 사용할 수 있다.

  • substring 사용
    public class ArnUtils {
    
      private static final String SLASH = "/";
      private static final String VERSION = SLASH + "versions";
    
      private ArnUtils() {
        throw new IllegalStateException("Utils Class");
      }
    
      @Getter @Setter @Builder
      public static class IdAndVersionId {
        String id;
        String versionId;
      }
    
      public static IdAndVersionId returnIdAndVersionId(String arn) {
        String id = arn.substring(0, arn.lastIndexOf(VERSION)).substring(arn.substring(0, arn.lastIndexOf(VERSION)).lastIndexOf(SLASH) + 1);
        String versionId = arn.substring(arn.lastIndexOf(SLASH) + 1);
    
        return IdAndVersionId.builder().id(id).versionId(versionId).build();
      }
    
    }
  • pattern, matcher 사용
    public class ArnUtils {
    
      private static final String ID_PATTERN = "\w{8}-\w{4}-\w{4}-\w{4}-\w{12}";
    
      private ArnUtils() {
        throw new IllegalStateException("Utils Class");
      }
    
      @Getter @Setter @Builder
      public static class IdAndVersionId {
        String id;
        String versionId;
      }
    
      public static IdAndVersionId returnIdAndVersionId(String arn) {
        List stringList = new ArrayList<>();
    
        Pattern pattern = Pattern.compile(ID_PATTERN);
        Matcher matcher = pattern.matcher(arn);
    
        while (matcher.find()) {
          stringList.add(matcher.group());
        }
    
        return IdAndVersionId.builder().id(stringList.get(0)).versionId(stringList.get(1)).build();
      }
    
    }

 

 

 

junit 을 이용해 호출해보면 pattern 과 matcher 의 사용법을 알 수 있다.

public void arnTest() {

    String arn = "arn:aws:greengrass:ap-northeast-2:519823736763:/greengrass/definition/subscriptions/33f89084-ae81-462f-afff-9dc149e2d666/versions/6da86ada-39e1-48ae-b577-9fb5aeb66ea8";

    Pattern pattern = Pattern.compile("\/subscriptions\/([a-z0-9\-]*)\/.*");
    Matcher matcher = pattern.matcher(arn);

    System.out.println("find : " + matcher.find());
    System.out.println("start : " + matcher.start());
    System.out.println("end : " + matcher.end());
    System.out.println("group : " + matcher.group());
    System.out.println("toMatchResult : " + matcher.toMatchResult());

}

 

 

 

 

 

반응형