如何使用转义字符从java文件中读取模式
我正在从一个文件中读取一些模式,并在字符串匹配方法中使用它。但是,当从文件中读取模式时,转义字符不起作用 例如,我几乎没有数据,例如“abc.1”、“abcd.1”、“abce.1”、“def.2” 如果字符串匹配“abc.1”,即abc,我想做一些活动。后跟任何字符或数字 我有一个文件,用于存储要匹配的模式,例如模式abc \* 但当我从文件中读取模式并在String matches方法中使用它时,它不起作用 有什么建议吗 演示该问题的示例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.
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
}