Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java正则表达式:在块内严格匹配两个字符串之间的文本_Java_Regex_Pattern Matching - Fatal编程技术网

Java正则表达式:在块内严格匹配两个字符串之间的文本

Java正则表达式:在块内严格匹配两个字符串之间的文本,java,regex,pattern-matching,Java,Regex,Pattern Matching,我需要一个正则表达式,它在两个字符串之间匹配,但只取内部块。我试着用不情愿的量词,但没用 以下是一个例子: <div> Hi </div> <div class = "quote"> This is mail. <hr tabindex="-1"> <div color="r"> <b>From:</b>xyz<br> <b>

我需要一个正则表达式,它在两个字符串之间匹配,但只取内部块。我试着用不情愿的量词,但没用

以下是一个例子:

<div>
    Hi
</div>
<div class = "quote">
    This is mail.
    <hr tabindex="-1">
    <div color="r">
        <b>From:</b>xyz<br>
        <b>Sent:</b>xyz PM<br>
        <b>To:</b>xyz<br><br>
    </div>
</div>

你好
这是邮件。

From:xyz
发送:xyz PM
至:xyz

我使用了这个正则表达式,但它不起作用(与DOTALL匹配,因此“.”也与换行符匹配)


不建议使用正则表达式解析HTML

如果您知道自己在做什么,那么您可以使用以下
String#replaceAll
调用:

html.replaceAll
           ("(?i)(?s).*?(<div\\s*color.*?From:.*?Sent:.*?To:.*?</div>).*", "$1");
html.replaceAll

(“(?i)(?s)。*?(试试这个。我正在扩展我的评论,让你明白我的意思:

  public String findText(String htmlString) {
    Pattern patt = Pattern.compile("<div.*</div>");
      Matcher m = patt.matcher(htmlString);
      while (m.find()) {
        String text = m.group(1);
        // check whether the value of text is the div you want
        if (text.indexOf("color") < text.indexOf(">")) { //... or something similar
           return (text);
        }
      }
    return null;
   }
公共字符串findText(字符串htmlString){
Pattern patt=Pattern.compile(“”){/…或类似的东西
返回(文本);
}
}
返回null;
}

如果您只是重复匹配
,然后使用一些Java代码看看是否找到了正确的代码。可能另一个正则表达式或一些
.indexOf()
调用。重复,直到找到正确的。我认为这不是一个好主意。问题是如果我重复调用

html.replaceAll
           ("(?i)(?s).*?(<div\\s*color.*?From:.*?Sent:.*?To:.*?</div>).*", "$1");
  public String findText(String htmlString) {
    Pattern patt = Pattern.compile("<div.*</div>");
      Matcher m = patt.matcher(htmlString);
      while (m.find()) {
        String text = m.group(1);
        // check whether the value of text is the div you want
        if (text.indexOf("color") < text.indexOf(">")) { //... or something similar
           return (text);
        }
      }
    return null;
   }