0

我正在尝试使用以下代码在我的 JTextPane 中识别字符串(这意味着双引号内的文本)

Pattern string= Pattern.compile("\"/\"/.*");
Matcher matcher = string.matcher(content);

while (matcher.find()) {
    document.setCharacterAttributes(matcher.start(), matcher.end() - matcher.start(), textPane.getStyle("red"), true);
}

但是上面的代码没有正确识别字符串。我认为我给出的模式是错误的。请帮助我纠正模式。

谢谢大家!我真的很感谢你的帮助!由于你们所有的答案都是正确的,我很难选择最佳答案,所以我给了你们每个人的一票。希望你不介意:)

再次感谢大家!我真的很感激:)

4

3 回答 3

1

正确的表达是这样的:

Pattern.compile("\"[^\"]*\"");
于 2012-05-10T15:45:35.797 回答
1
 String s = "jsdfjh shfslfh \"ksfsdkflsdaf\" 2346237846 ufhusdhfu usfhsdfis \"sadhgbshad78hgshd\" jhsdjs";
        Pattern p = Pattern.compile("\"{1}[.[^\"]]*\"{1}");
        Matcher m = p.matcher(s);
        while(m.find()){
            System.out.println(s.substring(m.start(), m.end()));
        }
于 2012-05-10T15:46:13.337 回答
1

我建议您使用的正则表达式是"[^"]*". 引用和转义,就是"\"[^\"]*\"".

所以试试

Pattern string= Pattern.compile("\"[^\"]*\"");

但请注意,这将无法正确找到包含双引号的字符串,因此我希望您JTextPane不包含 Java。

于 2012-05-10T15:54:40.520 回答