프로그래밍/Java

Java 정규식 + split

소행성왕자 2022. 2. 10. 16:43
json 만 추출하고 싶을때


        String sample = "CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.\n" +
                "[W NNPACK.cpp:79] Could not initialize NNPACK! Reason: Unsupported hardware.\n" +
                "/usr/local/lib64/python3.6/site-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at  /pytorch/c10/core/TensorImpl.h:1156.)\n" +
                "  return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)\n" +
                "CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.\n" +
                "CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.\n" +
                "CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.\n" +
                "CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.\n" +
                "CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.\n" +
                "CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.\n" +
                "CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.\n" +
                "CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.\n" +
                "{ \"colorsArray\":[{ \"colorName\":\"red\", \"hexValue\":\"#f00\" }, { \"colorName\":\"green\", \"hexValue\":\"#0f0\" }, { \"colorName\":\"blue\", \"hexValue\":\"#00f\" } ] }";
        

        String[] arr = output.split("\n");
        System.out.println(">>>>");
        System.out.println(arr.length);
        System.out.println(">>>>>");
        System.out.println(arr[arr.length-1]);
        String findJson = arr[arr.length-1];


        
        Pattern pattern = Pattern.compile("([{].*?[}]$)");
        Matcher matcher = pattern.matcher(sample);

        String findJson = "";
        while (matcher.find()) {
            System.out.println(matcher.group(1));
            findJson = matcher.group(1);
            if (matcher.group(1) == null) break;
        }