我正在研究一致性问题,我必须:“清理文件。为此,删除所有字符串文字(包括任何内容) 在双引号中,第二个引号前面没有奇数 反斜杠),删除所有//注释,删除所有分隔符 (看看这些)和运营商(看看这些)。不要担心“.class文字”(我们假设它们不会出现在输入文件中)。“
我想我知道replaceAll()方法是如何工作的,但我不知道文件中会有什么。对于初学者,我将如何删除所有字符串文字?有没有办法用两个双引号替换所有内容? I.E. String someString =“我想从文件中删除这个plz帮助我,thx”;
我目前将每行文本放在字符串的ArrayList中。
这是我得到的:http://pastebin.com/N84QdLqz
答案 0 :(得分:1)
我想我已经为你的字符串文字正则表达式提出了一个解决方案。类似的东西:
inputLine.replaceAll("\"([^\\\\\"]*(\\\\\")*)*([\\\\]{2})*(\\\\\")*[^\"]*\"");
应该做的伎俩。如果在Java有机会逃脱所有字符之后将正则表达式打印到控制台,则正则表达式实际上更具可读性。因此,如果您使用该字符串调用System.out.println()
,您将获得:
"([^\\"]*(\\")*)*([\\]{2})*(\\")*[^"]*"
我打破原来的正则表达式来解释。首先是:
"\"([^\\\\\"]*(\\\\\")*)*
这表示匹配引号字符("
)后跟0或更多字符模式,这些字符既不是反斜杠(\
)也不是引号字符("
),后面跟着0个或更多转义引号(\"
)。如您所见,由于\
通常用作Java中的转义字符,因此使用它们的任何正则表达式都会变得非常冗长。
([\\\\]{2})*
这表示接下来匹配0组或更多组2(即偶数数量)的反斜杠。
(\\\\\")*
这表示匹配单个反斜杠后跟引号字符,并在一起找到0个或更多。
[^\"]*\"
这表示匹配任何不是引号字符的内容,0或更多次,后跟引号字符。
我用类似于你要求的例子测试了我的正则表达式:
字符串文字(用双引号括起来的任何内容, second 之前没有奇数个反斜杠)
强调我的。因此,通过这种说法,如果文字中的第一个引号在它前面有反斜杠,那就不重要了。
String s = "This is "a test\" + "So is this"
将{regex与replaceAll
一起使用并替换为\"\"
,您将获得:
String s = ""a test\""So is this"
哪个应该是正确的。如果需要,您可以通过调用replaceAll
替换""
来完全删除匹配的文字引号:
String s = a test\So is this"
或者,使用这个正则表达式来做一些不那么令人头疼的事情:
String s = "This is \"a test\\" + "So is this"
将返回:
String s = +
答案 1 :(得分:0)
哟可以这样做:
private static final String REGEX = "(\"[\\w|\\s]*\")";
private static Pattern P;
private static Matcher M;
public static void main(String args[]){
P = Pattern.compile(REGEX);
//.... your code here ....
}
public static ArrayList<String> readStringsFromFile(String fileName) throws FileNotFoundException
{
Scanner scanner = null;
scanner = new Scanner(new File(fileName));
ArrayList<String> list = new ArrayList<>();
String str = new String();
try
{
while(scanner.hasNext())
{
str = scanner.nextLine();
str = cleanLine(str);//clean the line after read
list.add(str);
}
}
catch (InputMismatchException ex)
{
}
return list;
}
public static String cleanLine(String line) {
int index;
//remove comment lines
index = line.indexOf("//");
if (index != -1) {
line = line.substring(0, index);
}
//remove everything within two double quotes
M = P.matcher(line);
String tmp = "";
while(M.find()) {
tmp = line.substring(0,M.start());
tmp += line.substring(M.end());
line = tmp;
M = P.matcher(line);
}
return line;
}