Java模式/匹配器 [英] Java Pattern/ Matcher

查看:63
本文介绍了Java模式/匹配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是示例文本: \ 1f \ 1e \ 1d \ 020028 .我无法修改输入文本,我正在从文件中读取一长串文本.

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.

我要提取以下内容: \ 1f \ 1e \ 1d \ 02

I want to extract the following: \1f, \1e, \1d, \02

为此,我编写了以下正则表达式模式:"\\ [a-fA-F0-9]"

For this, I have written the following regular expression pattern: "\\[a-fA-F0-9]"

我正在使用 Pattern Matcher 类,但是我的匹配器无法使用上述正则表达式找到模式.我已经在一些在线正则表达式网站上用文本测试了此正则表达式,并且令人惊讶的是,它可以在其中工作.

I am using Pattern and Matcher classes, but my matcher is not able find the pattern using the mentioned regular expression. I have tested this regex with the text on some online regex websites and surprisingly it works there.

我要去哪里错了?

原始代码:

public static void main(String[] args) {
    String inputText = "\1f\1e\1d\02002868BF03030000000000000000S023\1f\1e\1d\03\0d";
    inputText        = inputText.replace("\\", "\\\\");

    String regex     = "\\\\[a-fA-F0-9]{2}";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(inputText);

    while (m.find()) {
        System.out.println(m.group());
    }
}

输出:什么都没打印

推荐答案

您需要正确阅读文件,并将'\'字符替换为'\\'.假设您的项目中有一个名为test_file的文件,其内容如下:

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());
        }
    }
}

这篇关于Java模式/匹配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆