Java 如何找到一个/*&引用;字符串中的字符

Java 如何找到一个/*&引用;字符串中的字符,java,Java,我试图使用.contains或.indexOf查找特定的字符串匹配,但当我在字符串中搜索“*/”或“/*”时,我无法找到该组合 例如: String exampleString = "/* SQL Comment */"; String commentStart = "/*"; String commentEnd = "*/"; if(exampleString.contains(commentStart) || exampleString.contains(commentEnd){ S

我试图使用.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注释。

是否尝试提取注释?如果是这样,您需要使用模式和匹配器。下面是一个示例实现:

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!'

假设在
if
块开始之前确实有2个
字符,则代码会打印该行。无需转义您正在查找的子字符串,因为
contains
没有将其参数视为正则表达式。您的第一个示例应该可以使用CharSequence,如中所述?正如其他注释所述,除了缺少括号外,您的第一个示例很好。你得到的结果与你期望的有什么不同?谢谢你的帮助。我刚刚测试了它,它确实有效,但奇怪的是,对于我正在查看的字符串,它仍然没有被找到。至少我找角色的方式没有问题。我的代码中一定有别的东西。不,我不想这么做。在这一点上,我只是想大体上找到它,但最终我需要做你写的事情。谢谢你花时间回答我的问题。这是代码中其他地方的一个问题,字符串没有到达我的代码中试图找到它。很抱歉浪费您的时间。没问题,我喜欢为Stackoverflow编写代码:)。