Java regex在源代码中查找if或while语句
我正在尝试创建一个正则表达式,它能够识别一些源代码的字符串表示形式中的if和while语句。然后,我将使用正则表达式反转与该语句关联的布尔条件,在适当的地方使用Java中的String.replace()函数插入“!(“and”)” 正则表达式应该能够识别if和while语句,而不考虑语句块的使用、条件有多少部分或条件的“嵌套”程度 换言之,正则表达式应认可以下所有语句:Java regex在源代码中查找if或while语句,java,regex,Java,Regex,我正在尝试创建一个正则表达式,它能够识别一些源代码的字符串表示形式中的if和while语句。然后,我将使用正则表达式反转与该语句关联的布尔条件,在适当的地方使用Java中的String.replace()函数插入“!(“and”)” 正则表达式应该能够识别if和while语句,而不考虑语句块的使用、条件有多少部分或条件的“嵌套”程度 换言之,正则表达式应认可以下所有语句: if(true) function(); if(true){ function(); } if((true &a
if(true)
function();
if(true){
function();
}
if((true && thing.isEmpty() || i > 2){
function();
}
if((true && thing.isEmpty()
|| i > 2){
function();
}
(以此类推,也包括等价的while语句)
我找到了一个正则表达式,它似乎适用于使用语句块的ifs和whiles:
"(if|while)[\\s]*[\\(]([^\\{])*\\{"
不幸的是,这个问题是,如果我正在处理的代码有一个if或while,它不使用块,那么正则表达式的([^\\{])*部分将吸收所有内容,直到找到下一个\\}
以下是我目前掌握的代码:
private static int negateBool(File inFile, File outFile, int numMuts){
// establish character counter
int charCounter = -1;
try{
// set up the output
if(!outFile.exists()){
outFile.createNewFile();
}
PrintWriter fileOut = new PrintWriter(new FileWriter(outFile.getPath()));
// convert input file into a string
Scanner scanner = new Scanner(inFile);
String content = scanner.useDelimiter("\\Z").next();
scanner.close();
String regex = "(if|while)[\\s]*([^\\{]*)\\{";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
int intCounter = numMuts;
while(matcher.find() && intCounter > -1){ // if a potential mutation has been found
System.out.println("ping");
if(intCounter > 0){ // if this mutation has been done already
intCounter--;
}
else{ // a new mutation has been found, intCounter == 0
charCounter = matcher.start(1);
// do the mutation
fileOut.write(content.substring(0,matcher.start(1)));
String part = content.substring(matcher.start(1), matcher.end(0));
part = part.replaceFirst(regex, "$1(!$2){");
fileOut.write(part);
fileOut.write(content.substring(matcher.end(0), content.length()));
intCounter = -1;
}
}
fileOut.close();
}catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return charCounter;
}
正是在这里,通过尝试使用正则表达式,一种快速的字符串匹配语言,来做一些它做不到的事情,即语法解析,你只会让事情变得不可能的困难。编写一个令牌读取器,跟踪它是否看到了if/while构造,并且可以为条件体添加开始/结束检测。这段代码的预期用途是什么?这个问题不可能用1个正则表达式来解决,甚至2个或更多的正则表达式都会很复杂,即使这样,也会有一些情况会破坏它(比如条件参数中的字符串或注释)。此外,您对正则表达式的使用向我表明,您对正则表达式的掌握非常薄弱(例如,并非所有内容都需要使用字符组:不必说
[\s]*
;您只需说\s*
)。我同意Lambda Fairy的观点;你试图以一种做作的方式做一些非常复杂的事情。