Java Pattern/ Matcher

前端 未结 4 996
既然无缘
既然无缘 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 08:56

    (answer changed after OP added more details)

    Your string

    String inputText = "\1f\1e\1d\02002868BF03030000000000000000S023\1f\1e\1d\03\0d";
    

    Doesn't actually contains any \ literals because according to Java Language Specification in section 3.10.6. Escape Sequences for Character and String Literals \xxx will be interpreted as character indexed in Unicode Table with octal (base/radix 8) value represented by xxx part.

    Example \123 = 1*82 + 2*81 + 3*80 = 1*64 + 2*8 + 3*1 = 64+16+3 = 83 which represents character S

    If string you presented in your question is written exactly the same in your text file then you should write it as

    String inputText = "\\1f\\1e\\1d\\02002868BF03030000000000000000S023\\1f\\1e\\1d\\03\\0d";
    

    (with escaped \ which now will represent literal).


    (older version of my answer)

    It is hard to tell what exactly you did wrong without seeing your code. You should be able to find at least \1, \1, \1, \0 since your regex can match one \ and one hexadecimal character placed after it.

    Anyway this is how you can find results you mentioned in question:

    String text = "\\1f\\1e\\1d\\020028";
    Pattern p = Pattern.compile("\\\\[a-fA-F0-9]{2}");
    //                                          ^^^--we want to find two hexadecimal 
    //                                               characters after \
    Matcher m = p.matcher(text);
    while (m.find())
        System.out.println(m.group());
    

    Output:

    \1f
    \1e
    \1d
    \02
    

提交回复
热议问题