我正在尝试使用.contains或.indexOf查找特定的字符串匹配,但是当我在字符串中搜索“* /”或“/ *”时,我无法找到该组合。
例如:
String exampleString = "/* SQL Comment */";
String commentStart = "/*";
String commentEnd = "*/";
if(exampleString.contains(commentStart) || exampleString.contains(commentEnd){
System.out.println("Comment: " + exampleString);
}
当我运行程序时,我没有收到评论。当我试图逃脱明星角色或削减角色时,仍然没有运气。
例如:
String exampleString = "/* SQL Comment */";
if(exampleString.contains("\\*\\/"){
System.out.println("Comment: " + exampleString);
}
你怎么能找到斜线星组合?我还想补充一点,这不是为了防止SQL注入攻击。这只是为了搜索SQL注释。
答案 0 :(得分:0)
您是否想要提取评论?如果是这样,你需要使用模式和匹配器。这是一个示例实现:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String exampleString = "/* SQL Comment */ Some text /* Another SQL comment */ /* A comment without end!";
Pattern start = Pattern.compile("/\\*");
Pattern end = Pattern.compile("\\*/");
Matcher startMatcher = start.matcher(exampleString);
Matcher endMatcher = end.matcher(exampleString);
while(startMatcher.find()) {
int startIndex = startMatcher.end();
int endIndex = exampleString.length();
System.out.println("Start index: " + startIndex);
if(endMatcher.find()) {
endIndex = endMatcher.start();
System.out.println("End index: " + endIndex);
} else {
System.out.println("Comment does not end");
}
System.out.println("String: '" + exampleString.substring(startIndex, endIndex) + "'");
}
}
}
输出:
Start index: 2
End index: 15
String: ' SQL Comment '
Start index: 30
End index: 51
String: ' Another SQL comment '
Start index: 56
Comment does not end
String: ' A comment without end!'