如何在Java中逐个转义正则表达式元字符?
我正在为一个Android应用程序工作,处理包含许多正则表达式认为具有特殊含义的字符的文件,包括\?.()[*\^+'
和-
。我将读取两个文件:
- 单词字典列表,每个单词占一行。
- 可以用于过滤单词字典列表中单词的字符列表。
以下是每个的示例。
字典:
/it*
t1*]
?\<t
item
(是的,这些都是单词。前三个是缩写的盲文ASCII表示法,分别代表“针脚”,“老师”和“思考”。现在你知道了。)
要使用的“字母”:
?]*/\<1eitm
我希望将这些字母包含在一个类似于这样的正则表达式中:
String letters = "?]*/\<1eitm";
Pattern pattern = Pattern.compile("^["+letters+"]{4}$", Pattern.MULTILINE);
我的目标是从字典列表中选择所有只包含给定字符且长度为指定长度的单词。我无法控制请求字符在文件中出现的顺序。
如果我只使用非元字符,如<1eitm>,那么这个问题可以很好地解决。不知何故,我需要转义元字符,并确保字符,如]和-出现在方括号内的正确位置。
我可以手动完成这个过程,但希望有一个内置的命令来替代我完成这个任务。到目前为止,我找到的所有命令中只有Pattern.quote()命令不能给我想要的结果。
以下是我可能需要在方括号内使用的所有字符列表:
\_-,;:!?.'"()[]@*/\&#%^+<=>~$0123456789abcdefghijklmnopqrstuvwxyz
以下是我在Android测试中使用的基本代码:
package com.example.quote;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AssetManager am = this.getAssets();
try {
String dictionary = readFile(am, "dictionary.txt");
String regex = readFile(am, "regex.txt");
regex = "^["+regex+"]{4}$"; // THIS IS WHERE I NEED TO MAKE A CHANGE
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(dictionary);
while (matcher.find()) {
Log.d("TEST", matcher.group(0));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String readFile(AssetManager am, String fileName) throws IOException {
InputStream is = am.open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String string = new String(buffer, "UTF-8");
return string;
}
}