Java Pattern/ Matcher

前端 未结 4 1047
既然无缘
既然无缘 2021-01-14 08:42

This is a sample text: \\1f\\1e\\1d\\020028. I cannot modify the input text, I am reading long string of texts from a file.


I wan

4条回答
  •  误落风尘
    2021-01-14 09:03

    You need to read the file properly and replace '\' characters with '\\'. Assume that there is file called test_file in your project with this content:

    \1f\1e\1d\02002868BF03030000000000000000S023\1f\1e\1d\03\0d
    

    Here is the code to read the file and extract values:

    public static void main(String[] args) throws IOException, URISyntaxException {        
        Test t = new Test();
        t.test();
    }
    
    public void test() throws IOException {        
        BufferedReader br =
            new BufferedReader(
                new InputStreamReader(
                    getClass().getResourceAsStream("/test_file.txt"), "UTF-8"));
        String inputText;
    
        while ((inputText = br.readLine()) != null) {
            inputText = inputText.replace("\\", "\\\\");
    
            Pattern pattern = Pattern.compile("\\\\[a-fA-F0-9]{2}");
            Matcher match = pattern.matcher(inputText);
    
            while (match.find()) {
                System.out.println(match.group());
            }
        }
    }
    

提交回复
热议问题