有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

匹配器。find()正则表达式Java函数

考虑下面的代码,检查输入是否为表单:^ {< CD1>} 如果以上述形式输入,则打印标签之间的内容,否则打印无

例如:

  1. 输入:<h1>Nayeem loves counseling</h1> 输出:纳伊姆喜欢咨询

  2. 输入:<h1><h1>Sanjay has no watch</h1></h1><par>So wait for a while</par> 输出:桑杰没有手表 所以等一会儿

  3. 输入:<Amee>safat codes like a ninja</amee> 输出:无

String line = scan.nextLine();

boolean matchFound = false;
Pattern r = Pattern.compile("<(.+)>([^<]+)</\\1>");
Matcher m = r.matcher(line);

while(m.find()) {
    System.out.println(m.group(2));
    matchFound = true;
}

if(!matchFound) {
    System.out.println("None");
}

这里find()返回布尔类型。我的问题是为什么find()应该与while循环一起使用?为什么我不能用“如果”来代替while?find如何在内部工作


共 (2) 个答案

  1. # 1 楼答案

    当您调用find()时,匹配器将尝试查找与您的正则表达式模式匹配的下一个序列。通过在while循环中使用find(),您将能够获得所有匹配序列(如果有)。如果希望将输入字符串作为一个整体进行匹配,可以使用matches()

    参考:

    find method in Java Docs

    matches method in Java Docs

  2. # 2 楼答案

    答案在javadoc中表示find

    public boolean find()

    Attempts to find the next subsequence of the input sequence that matches the pattern.

    This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

    If the match succeeds then more information can be obtained via the start, end, and group methods.

    您正在查看的代码是反复查找正则表达式的下一个匹配项并打印匹配的第二组。因为匹配的第二组是标签内容,所以这会打印所有标签的内容

    如果使用if而不是while,则只打印第一个匹配项;i、 e.仅第一个标签的内容