본문 바로가기
Java 문제

[Java] 문자열이 따옴표(“ 또는 ‘)로 쌓였는지 검사

by 두리두리안 2021. 5. 7.
package Test01;

import java.util.regex.Pattern;

public class problem_No1_3 {

    public static void main(String[] args) throws Exception {

        String startSingleQ = "\'문장";
        String startDoubleQ = "\"문장";
        String endSingleQ = "문장\'";
        String endDoubleQ = "문장\"";
        String startSQEndDQ = "\'문장\"";
        String startDQEndSQ = "\"문장\'";
        String SQ = "\'문장\'";
        String DQ = "\"문장\"";

        solutionRegex(startSingleQ);
        solutionRegex(startDoubleQ);
        solutionRegex(endSingleQ);
        solutionRegex(endDoubleQ);
        solutionRegex(startSQEndDQ);
        solutionRegex(startDQEndSQ);
        solutionRegex(SQ);
        solutionRegex(DQ);
        System.out.println("**************************************");
        solutionStringMethod(startSingleQ);
        solutionStringMethod(startDoubleQ);
        solutionStringMethod(endSingleQ);
        solutionStringMethod(endDoubleQ);
        solutionStringMethod(startSQEndDQ);
        solutionStringMethod(startDQEndSQ);
        solutionStringMethod(SQ);
        solutionStringMethod(DQ);
    }

    public static void solutionRegex(String str) {

        Pattern pattern1 = Pattern.compile("\"[^\"\"]+\"");
        Pattern pattern2 = Pattern.compile("\'[^\'\']+\'");
        String str1Result = pattern1.matcher(str).find() ? "\"\"로 둘러쌓여있습니다"
                : pattern2.matcher(str).find() ? "\'\'로 둘러쌓여있습니다" : "해당 하는것이 없습니다.";
        System.out.println("결과 값" + str1Result);

    }

    public static void solutionStringMethod(String str) {

        if (str.startsWith("\"") & str.endsWith("\"")) {
            System.out.println("결과 값 : \"\"로 둘러쌓여있습니다");
        } else if (str.startsWith("\'") & str.endsWith("\'")) {
            System.out.println("결과 값 : \'\'로 둘러쌓여있습니다");
        } else {
            System.out.println("해당 하는것이 없습니다.");
        }
    }
}