如何编写包含双引号(“)的Java字符串文字?

时间:2010-03-10 20:17:51

标签: java regex compiler-errors

我收到编译时错误。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class gfile
 {
  public static void main(String args[]) {
    // create a Pattern
    Pattern p = Pattern.compile("<div class="dinner">(.*?)</div>");//some prob with this line


    // create a Matcher and use the Matcher.group() method
  String can="<tr>"+
                          "<td class="summaryinfo">"+

                                "<div class="dinner">1,000</div>" +
                                "<div style="margin-top:5px " +
                                 "font-weight:bold">times</div>"+
                            "</td>"+
                        "</tr>";

    Matcher matcher = p.matcher(can);
    // extract the group

    if(matcher.find())
     {
    System.out.println(matcher.group());
     }
  else
     System.out.println("could not find");
  }
}

5 个答案:

答案 0 :(得分:7)

你对Pattern.compile的调用中有未转义的引号。

变化:

Pattern p = Pattern.compile("<div class="dinner">(.*?)</div>");

要:

Pattern p = Pattern.compile("<div class=\"dinner\">(.*?)</div>");

注意:我刚刚在String中看到了同样的问题。

将其更改为:

  String can="<tr>"+
                      "<td class=\"summaryinfo\">"+

                            "<div class=\"dinner\">1,000</div>" +
                            "<div style=\"margin-top:5px " +
                             "font-weight:bold\">times</div>"+
                        "</td>"+
                    "</tr>";

我不知道这是否能修复它,但现在至少会编译。

答案 1 :(得分:1)

但是,你的正则表达式匹配(。*?)“任意字符,任意数量的重复,尽可能少”

意思是,它什么都不匹配......以及一切。

...或您的报价未转义的事实。

答案 2 :(得分:0)

您应该使用HTML解析器来解析和处理HTML - 而不是正则表达式。

答案 3 :(得分:0)

正如已经指出的那样,你需要在字符串的 all 中转义双引号。

而且,如果您希望获得“1,000”,则需要使用group(1),否则您将获得该模式的完全匹配。

结果代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class gfile
 {
  public static void main(String args[]) {
    // create a Pattern
    Pattern p = Pattern.compile("<div class=\"dinner\">(.*?)</div>");

    // create a Matcher and use the Matcher.group() method
    String can="<tr>"+
                          "<td class=\"summaryinfo\">"+

                                "<div class=\"dinner\">1,000</div>" +
                                "<div style=\"margin-top:5px " +
                                 "font-weight:bold\">times</div>"+
                            "</td>"+
                        "</tr>";

    Matcher matcher = p.matcher(can);

    if(matcher.find())
    {
       System.out.println(matcher.group(1));
    }
    else
       System.out.println("could not find");
  }
}

答案 4 :(得分:-1)

(.*?)可能需要(.*)?

相关问题