ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 정규표현식,Arrays,java.lang 패키지
    JAVA 2021. 7. 23. 10:00

    정규표현식(RegularExpression) 작성 방법

    문자열이 정해져 있는 형식으로 구성되어 있는지 검증할 때 사용

    문자또는 숫자 기호와 반복 기호가 결합된 문자열

    1. [] : 한개의 문자, [abc]는 a,b,c중 하나의 문자, [^abc]는 a,b,c이외의 문자를 의미

    2. \d : 한개의 숫자 [0-9]와 동일

    3. \w : 한개의 알파벳문자 또는 한개의 숫자 [a-zA-Z_0-9]

    4. \s : 공백

    5. ? : 없거나 한개

    6. * : 없거나 한개이상

    7. + : 한개이상

    8. {n}: n개의 문자

    9. {n,}: 최소한 n개

    10. {n,m} : n개부터 m개까지

    11. () : 그룹핑

    12. ^ : 문자열의 시작

    13. $ : 문자열의 종료

    [자주 쓰이는 패턴]

    1) 숫자만 : ^[0-9]*$
    2) 영문자만 : ^[a-zA-Z]*$
    3) 한글만 : ^[가-힣]*$
    4) 영어 & 숫자만 : ^[a-zA-Z0-9]*$
    5) E-Mail : ^[a-zA-Z0-9]+@[a-zA-Z0-9]+$
    6) 휴대폰 : ^01(?:0|1|[6-9]) - (?:\d{3}|\d{4}) - \d{4}$
    7) 일반전화 : ^\d{2,3} - \d{3,4} - \d{4}$
    8) 주민등록번호 : \d{6} \- [1-4]\d{6}
    9) IP 주소 : ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3})

    ex)이메일, 전화번호, 비밀번호

    정규표현식과 Pattern클래스(java.util.regex.Pattern)

    문자열이 정해져 있는 형식(regex=Regular Expression 정규표현식)으로 구성되어

    있는지 검증할 때 사용한다.

    정규표현식을 작성하는 방법은 API에서 java.util.regex.Pattern클래스를 참조하면 된다.

    간단히 말해서 정규표현식은 문자 또는 숫자와 반복기호가 결합된 문자열이다.

    예를 들어서 02-123-4567 or 010-1234-5678과 같은 전화번호를 표현한 정규식은

    그룹(),연결대시출력-, \d숫자, {}반복갯수, \w단어 대문자도 가능 0,9도 가능 _도 가능 \w+문자반복,

    ? 없거나 한개, \. 그냥 점, @그냥 골뱅이

    {}반복갯수가 여러개일 경우 작은수부터 큰수 순서로..{3|4}

    전화번호일 경우: (02|010)-\\d{3,4}-\\d{4}

    이메일 경우: white@google.com -> \\w+@\\w.(\\.\\w+)?


    배열(Arrays)

    Arrays 클래스

    Arrays 클래스는 배열에 관한 조작기능을 지원한다. 배열의 복사, 배열항목의 정렬

    항목검색과 같은 기능을 제공하는 메서드를 가지고 있다.

    단순한 배열복사는 System.arraycopy()​ 메서드를 사용할 수 있으나 Arrays는 추가적

    으로 항목정렬, 검색, 비교와 같은 기능을 제공한다.

    Arrays관련 모든 메서드는 static이므로 Arrays클래스로 바로 접근할 수 있다.


    java.lang

    포장객체(Wrapper)

    자바는 기본타입(byte,int....double,boolean)은 객체로 생성할 수 없기 때문에 기본타입의

    데이터를 객체로 생성할 수 있도록 하는데 이런 객체를 포장객체라고 한다.

    이름에서 알 수 있듯이 기본타입의 값을 내부에 두고 포장하기 때문에 포장객체라고 한다.

    포장객체는 포장하고 있는 내부의 기본타입의 값은 외부에서 변경할 수 없다. 만약 내부의 값

    을 변경하고 싶을 경우에는 새로운 포장객체를 만들어야 한다.

    포장클래스는 java.lang.패키지에 포함되어 있는데 기본타입에 대응하는 각각의 클래스가 있다.

    char와 int는 각각 Character, Integer로 변경되고 나머지는 기본타입의 첫글자를 대문자로 바꾼

    이름의 클래스를 가지고 있다.

    기본자료형 대신에 포장클래스를 사용하는 이유

    1. 객체 또는 클래스가 제공하는 메서드를 사용할 수 있다.(parseInt() 등등)

    2. 클래스가 제공하는 상수를 사용할 수 있다.(MIN_VALUE, MAX_VALUE)

    3. 숫자, 문자로의 형변환 또는 진법변환시에 사용할 수 있다.

    Boxing, Unboxing?

    기본타입의 값을 포장객체로 만드는 과정을 Boxing 이라고 하고 반대로 포장객체에서 기본타입의

    값을 얻어내는 과정을 Unboxing 이라고 한다.

    박싱방법, 언박싱방법 : 아래참조!!

    자동박싱과 자동언박싱?

    기본타입의 값을 직접 박싱, 언박싱하지 않아도 자동적으로 박싱과 언박싱이 되는 것을 말한다.

    자동박싱은 포장클래스에 기본값이 대입이 되는 경우를 말하고 자동언박싱은 기본타입에 포장객체

    가 대입이 되는 경우에 발생한다.


     

    Math 클래스

    java.lang.Math 클래스는 수학계산에 사용할 수 있는 메서드를 제공한다.

    Math클래스의 메서드는 모두 static 메서드이므로 클래스이름으로 바로 사용이 가능하다.

    Random 클래스

    java.util.Random 클래스는 다양한 난수를 얻기 위해 다양한 메서드를 제공한다.

    Math.random() 메서드는 0 <= 난수 < 1 사이의 실수타입의 난수 1개를 얻는데만 사용

    하는 반면에 Random 클래스는 boolean, long, float, double 등의 난수를 얻을 수

    있다. 또 다른 차이점은 Random 클래스는 seed(종자)값을 지정할 수 있다.

    seed값을 지정하면 난수가 발생할 때 항상 동일한 난수값을 얻을 수가 있다.

     

    Date, Calendar

    +SimpleDateFormat클래스

    import java.util.Date;

    import java.sql.Date;(x) 사용법다르므로 주의

     

    DecimalFormat, LocalDate,LocalDateTime

    DecimalFormat: 숫자 형식주기(ex. 천단위마다 , 소수점 몇자리까지 보이기)


    정규식

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    import java.util.regex.Pattern;
     
    public class RePatternMain {
     
        public static void main(String[] args) {
            // 1. 전화번호 유효성체크
            String regExp = "()";
            String data = "010-1234-1234";
     
            boolean result = Pattern.matches(regExp, data); // data가 regExp에 일치하는지 안하는지
            System.out.println(result); // false
     
            regExp = "(02|010|031)";
            data = "031";
            result = Pattern.matches(regExp, data);
            System.out.println(result); // true
     
    //        \d 본인자체에 백슬래시 있으므로 이스케이프문자들은 백슬래시를 더해야해서 두개이다.
            regExp = "(02|010|031)-\\d{3,4}-\\d{4}";
            data = "031-1234-1234";
            result = Pattern.matches(regExp, data);
            System.out.println(result); // true
     
            if (result) {
                System.out.println("정상적인 전화번호입니다.");
            } else {
                System.out.println("비정상적인 전화번호입니다. 다시 입력하세요!");
            }
     
            result = Pattern.matches(regExp, "051-123-1234");
            System.out.println(result); // false
     
            // 2. 이메일 유효성체크
            regExp = "\\w+@\\w+\\.\\w+(\\.\\w+)?";
            data = "white@google.com";
     
            result = Pattern.matches(regExp, data);
            System.out.println(result); // true
            
            if (result) {
                System.out.println("정상적인 이메일입니다.");
            } else {
                System.out.println("비정상적인 이메일입니다. 다시 입력하세요!");
            }
     
        }
    }
     
    cs

    배열1

    복사

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    public class ArraysCopyMain {
     
        public static void main(String[] args) {
     
            char[] arr1 = { 'J''A''V''A' };
     
            // 1. Arrays.copyOf(복사할배열, 복사할길이 -= 1)
            char[] arr2 = Arrays.copyOf(arr1, arr1.length);// arr1.length = 4,
            System.out.println(arr2);// 출력: JAVA
     
            // 2. Arrays.copyOfRange(복사할배열, from, to -= 1)
            char[] arr3 = Arrays.copyOfRange(arr1, 13);
            System.out.println(arr3); // 출력: AV
            System.out.println(Arrays.toString(arr3)); // 출력:[A, V]
     
            // 3. System.arraycopy(복사할배열, from, 복사해놓을배열, from, 길이)
            char[] arr4 = new char[arr1.length];
            System.arraycopy(arr1, 0, arr4, 0, arr1.length);
            System.out.println(Arrays.toString(arr4)); // 출력: [J, A, V, A]
            for (int i = 0; i < arr4.length; i++) {
                System.out.println(arr4[i]);
            }
     
        }
    }
    cs

    배열2

    비교하여 정렬 및 검색

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    public class ArraysCopyMain {
     
        public static void main(String[] args) {
     
            char[] arr1 = { 'J''A''V''A' };
     
            // 1. Arrays.copyOf(복사할배열, 복사할길이 -= 1)
            char[] arr2 = Arrays.copyOf(arr1, arr1.length);// arr1.length = 4,
            System.out.println(arr2);// 출력: JAVA
     
            // 2. Arrays.copyOfRange(복사할배열, from, to -= 1)
            char[] arr3 = Arrays.copyOfRange(arr1, 13);
            System.out.println(arr3); // 출력: AV
            System.out.println(Arrays.toString(arr3)); // 출력:[A, V]
     
            // 3. System.arraycopy(복사할배열, from, 복사해놓을배열, from, 길이)
            char[] arr4 = new char[arr1.length];
            System.arraycopy(arr1, 0, arr4, 0, arr1.length);
            System.out.println(Arrays.toString(arr4)); // 출력: [J, A, V, A]
            for (int i = 0; i < arr4.length; i++) {
                System.out.println(arr4[i]);
            }
     
        }
     
    }
     
    cs

    포장객체(Wrapper)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    public class BoxingUnBoxingMain {
     
        public static void main(String[] args) {
     
            int num = 100;
    //        num. 기본 타입이라 객체들처럼 메서드, 필드, 생성자등이 없다.
            Integer obj1 = new Integer(100);
    //        obj1. 객체라 메서드,필드,생성자등이 있다.
            System.out.println(obj1.MAX_VALUE);// final 상수
            System.out.println(obj1.MIN_VALUE);// final 상수
     
            // 1. 수동박싱
            Integer obj2 = new Integer(100);// 생성자이용
            Integer obj3 = Integer.valueOf("100");// 메서드이용: 문자열도 변환
            Integer obj4 = Integer.valueOf(100);// 메서드이용
     
            // 2. 수동언박싱 : 기본타입명+Value()
            int val1 = obj1.intValue();
            int val2 = obj2.intValue();
            int val3 = obj3.intValue();
            
            // 3. 자동박싱
            Integer obj = 100;
            
            // 4. 자동언박싱
            int result1 = obj;
            int result2 = obj + 100;
            System.out.println(result2);
            
        }
    }
     
    cs

    Math

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    public class MathMain {
     
        public static void main(String[] args) {
     
            // 1. ceil() :올림, 가장 큰 정수값
            double v1 = Math.ceil(5.1);
            System.out.println(v1); //6.0
     
            // 2. floor() :내림, 가장 작은 정수값
            v1 = Math.floor(5.1);
            System.out.println(v1); //5.0
     
            // 3. min(), max() : 두 숫자중 작은수, 큰수
            v1 = Math.max(47);
            System.out.println(v1); //7.0
            v1 = Math.min(47);
            System.out.println(v1); //4.0
            
            // 4. rint() : 반올림, 가장 가까운 정수값
            v1 = Math.rint(5.9);
            System.out.println(v1); //6.0
            v1 = Math.rint(5.3);
            System.out.println(v1); //5.0
            
            // 5. random()
            v1 = Math.random();
            System.out.println(v1);//0 ~ 1미만
            System.out.println(Math.random()*45 + 1);//0+1 ~ 45+1미만, 즉 1~45
            
            // 6. round()
            v1 = Math.round(5.7);
            System.out.println(v1); //6.0
            v1 = Math.round(5.3);
            System.out.println(v1); //5.0
            
        }
    }
    cs

    Random

    Math.random() 과 대표적으로 다른 부분: seed 값

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import java.util.Random;
    public class RandomMain {
     
        public static void main(String[] args) {
     
            Random random = new Random();
            System.out.println(random.nextInt());
            // 그냥 random객체 넣으면 주소값 .. toString이 재정의 되어 있지 않음.
     
            int[] selectNumber = new int[6];
            random = new Random(42);                    //seed값을 지정하는 순간 그 seed값을 가진 변수들은 다 똑같은 난수를 가진다.
            System.out.print("로또당첨번호: ");
            for (int i = 0; i < 6; i++) {
                selectNumber[i] = random.nextInt(45+ 1;// nextInt(n) n미만까지의 난수를 리턴
                System.out.print(selectNumber[i] + ",");
            }
     
        }
    }
    cs

    Date

    SimpleDateFormat

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    public class DateMain {
     
        public static void main(String[] args) {
            Date now = new Date();
            String str1 = now.toString();
            System.out.println(str1);
            
            //SimpleDateFormat
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");//MM: 월, mm: 분
            System.out.println(sdf1.format(now));
            sdf1 = new SimpleDateFormat("yyyy년 MM월 dd일 hh시 mm분 ss초");
            System.out.println(sdf1.format(now));
        }
     
    }
    cs

    Calendar

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    public class CalendarMain {
     
        public static void main(String[] args) {
     
            Calendar now = Calendar.getInstance(); // private 생성자 = 싱글톤, 메서드로 가져와야 한다.
            int year = now.get(Calendar.YEAR); // Calendar의 상수
            int month = now.get(Calendar.MONTH);
            int day = now.get(Calendar.DAY_OF_MONTH);
            System.out.println(year + "." + month + "." + day);
     
            int week = now.get(Calendar.DAY_OF_WEEK); // 숫자가 들어감: 1~7 일~토
            System.out.println(week);
            String str = null;
            switch (week) {// 즉, week 숫자(1~7)에 따라 str에서 어떤 글자가 나오는지
            case Calendar.MONDAY:
                str = "월";
                break;
            case Calendar.TUESDAY:
                str = "화";
                break;
            case Calendar.WEDNESDAY:
                str = "수";
                break;
            case Calendar.THURSDAY:
                str = "목";
                break;
            case Calendar.FRIDAY:
                str = "금";
                break;
            case Calendar.SATURDAY:
                str = "토";
                break;
            case Calendar.SUNDAY:
                str = "일";
                break;
            }
            System.out.println(str);
     
            int ampm = now.get(Calendar.AM_PM);
            System.out.println(Calendar.AM + "/" + Calendar.PM + "/" + Calendar.AM_PM);    //AM: 0, PM: 1, AM_PM: 9
     
            if (ampm == Calendar.AM) {
                System.out.println("오전입니다.");
            } else {
                System.out.println("오후입니다.");
            }
     
            int hour = now.get(Calendar.HOUR);
            int minute = now.get(Calendar.MINUTE);
            int second = now.get(Calendar.SECOND);
            System.out.println(hour + ":" + minute + ":" + second);
     
        }
    }
    cs

    DecimalFormat

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    import java.text.DecimalFormat;
     
    public class DecimalFormatMain {
     
        public static void main(String[] args) {
            
            double num = 1234567.89;
            
            DecimalFormat df = new DecimalFormat();
            System.out.println(df.format(num));//1,234,567.89
            
            df = new DecimalFormat("0");
            System.out.println(df.format(num));//1234568 소수점 한자리에서 반올림
            
            df = new DecimalFormat("0.0");
            System.out.println(df.format(num));//1234567.9 소수점 둘째자리에서 반올림
            
            df = new DecimalFormat("0.00000000000");
            System.out.println(df.format(num));//1234567.89000000000
            
            df = new DecimalFormat("#");
            System.out.println(df.format(num));//1234568 소수점 한자리에서 반올림 위의 0형식과 비슷하지만 차이점은 아래
            
            df = new DecimalFormat("######.######");
            System.out.println(df.format(num));//1234567.89 즉 0.0000..은 없는 자리는 0자리로 채움
            
            df = new DecimalFormat("#,###.0;-#,###.0");
            System.out.println(df.format(num));//1,234,567.9
        
            df = new DecimalFormat("#.#%");
            System.out.println(df.format(num));//123456789%
        }
     
    }
    cs

    LocalDate, LocalDateTime

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    import java.time.LocalDate;
    import java.time.LocalDateTime;
     
    public class DateTimeInfoMain {
     
        public static void main(String[] args) {
     
            LocalDateTime now = LocalDateTime.now();// 현재시간과 객체 리턴?
            System.out.println(now);
     
            String strDateTime = now.getYear() + "년 ";
            strDateTime += now.getMonth() + " "// 월 영어
            strDateTime += now.getMonthValue() + "월 "// 월 한국어
            strDateTime += now.getDayOfWeek() + " "// 요일 영어
            strDateTime += now.getHour() + "시 ";
            strDateTime += now.getMinute() + "분 ";
            strDateTime += now.getSecond() + "초 ";
            strDateTime += now.getNano() + "나노초 ";
            System.out.println(strDateTime);
     
            LocalDate nonDate = now.toLocalDate();// 년-월-일
            System.out.println(nonDate);
            if (nonDate.isLeapYear()) {
                System.out.println("윤년입니다.");
            } else {
                System.out.println("평년입니다.");
            }
     
            // 날짜연산
            now = LocalDateTime.now();
            LocalDateTime target = now.plusYears(1).minusMonths(2).plusDays(3).plusHours(4).minusMinutes(5).plusSeconds(10);
            // 현재 날짜에서 +, - 연산이 가능하다.
            System.out.println(target);
     
            //시간을 직접 지정 가능하다.
            target = now.withYear(2024).withMonth(12).withHour(10);
            System.out.println(target);
        }
    }
    cs

    'JAVA' 카테고리의 다른 글

    Collection FrameWork,Stream  (0) 2021.07.23
    Thread, Generic, Lambda, Collection Framework  (0) 2021.07.23
    java.lang.Object 클래스  (0) 2021.07.23
    인터페이스, 내부클래스, 예외  (0) 2021.07.23
    상속, instanceof, 추상, interface  (0) 2021.07.22

    댓글

Designed by Tistory.