如何使用转义字符从java文件中读取模式

如何使用转义字符从java文件中读取模式,java,regex,string,file-io,Java,Regex,String,File Io,我正在从一个文件中读取一些模式,并在字符串匹配方法中使用它。但是,当从文件中读取模式时,转义字符不起作用 例如,我几乎没有数据,例如“abc.1”、“abcd.1”、“abce.1”、“def.2” 如果字符串匹配“abc.1”,即abc,我想做一些活动。后跟任何字符或数字 我有一个文件,用于存储要匹配的模式,例如模式abc \* 但当我从文件中读取模式并在String matches方法中使用它时,它不起作用 有什么建议吗 演示该问题的示例java程序如下: package com.test.

我正在从一个文件中读取一些模式,并在字符串匹配方法中使用它。但是,当从文件中读取模式时,转义字符不起作用

例如,我几乎没有数据,例如“abc.1”、“abcd.1”、“abce.1”、“def.2”

如果字符串匹配“abc.1”,即abc,我想做一些活动。后跟任何字符或数字 我有一个文件,用于存储要匹配的模式,例如模式abc \*

但当我从文件中读取模式并在String matches方法中使用它时,它不起作用

有什么建议吗

演示该问题的示例java程序如下:

package com.test.resync;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestPattern {

    public static void main(String args[]) {
        // raw data against which the pattern is to be matched
        String[] data = { "abc.1", "abcd.1", "abce.1", "def.2" };

        String regex_data = ""; // variable to hold the regexpattern after
        // reading from the file

        // regex.txt the file containing the regex pattern
        File file = new File(
                    "/home/ekhaavi/Documents/WORKSPACE/TESTproj/src/com/test/regex.txt");

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String str = "";
            while ((str = br.readLine()) != null) {
                if (str.startsWith("matchedpattern")) {
                    regex_data = str.split("=")[1].toString(); // setting the
                                                               // regex pattern

                    }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        /*if the regex is set by the below String literal it works fine*/

        //regex_data = "abc\\..*"; 

        for (String st : data) {
            if (st.matches(regex_data)) {
                System.out.println(" data matched "); // this is not printed when the pattern is read from the file instead of setting it through literals
            }
        }
    }

}
regex.txt文件包含以下条目

matchedpattern=abc\..*/p>使用方法:

还有一些你应该考虑解决的问题:

  • 您正在覆盖
    while
    循环中
    regex\u数据的值。您是否打算将所有正则表达式模式存储在
    列表中

  • String#split()[0]
    将仅返回
    字符串。您不需要在这个问题上调用
    toString()


感谢您的帮助和建议,它按照要求工作
if (st.matches(Pattern.quote(regex_data))) {
     System.out.println(" data matched "); // this is not printed when the pattern is read from the file instead of setting it through literals
}