JTextPane:识别字符串

时间:2012-05-10 15:30:56

标签: java regex

我正在尝试使用以下代码在我的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);
}

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

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

再次感谢所有人!我真的很感激它:)

3 个答案:

答案 0 :(得分:1)

正确的表达方式是:

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

答案 1 :(得分: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()));
        }

答案 2 :(得分:1)

我建议你使用的正则表达式是"[^"]*"。引用和转义,来到"\"[^\"]*\""

所以试试

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

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