0
public static String convert(String str)
{
  if (str.equals("# "))
     System.out.println(" ");
  Pattern pattern = Pattern.compile("(#+[^#]+)");
  Matcher matcher = pattern.matcher(str);

  while (matcher.find())
  {
     String str1 = matcher.group(1);
     if (str1.replaceFirst("#+", "").length() == 0 || str1.replaceFirst("#+", "").matches("[\\s]+"))
        continue;
     int n = str1.length() - str1.replaceFirst("#+", "").length();
     System.out.println("<h" + n + ">" + str1.substring(n) + "</h" + n + ">");
  }
  char carac;
  carac = str.charAt(0);
  if (carac >= 65 && carac <= 90)
  {
     System.out.println("<p>");
     System.out.println(str);
     System.out.println("</p>");
  }
  return ("");
}

如何将while(matcher.find与 this结合起来,if(carac>=以便获得以下输出:< p> < h2> 分贝</ h2> </ p> 对于此输入:##Decibel??? (取而代之的是,我得到 <h2> 分贝</h2>。我正在制作一种算法,其中“#”在句子的开头被识别并根据情况变成 <h1></h1> 或 <hn>关于出现的#个数,然后算法识别句首是否有大写字母,如果有,则在段落的开头和结尾添加<p></p>。大问题我有,是我希望能够将两者结合起来。所以假设我会有#Appendix,我希望它转换为 <p> <h1> 附录</h1> </p>

谢谢

4

1 回答 1

0
   public static String convert(String str)
 {
   if (str.equals("# "))
      System.out.println(" ");
   Pattern pattern = Pattern.compile("(#+[^#]+)");
   Matcher matcher = pattern.matcher(str);

   while (matcher.find())
   {
       boolean append_p = false;
       char carac;
        for(int i = 0; i < str.length(); i++){
       if(Character.isLetter(str.charAt((i)))){
           if (Character.isUpperCase(str.charAt(i)))
           {
              System.out.print("<p>");
              append_p = true;
              break;
           }
       }else{
           append_p = false;
       }
   }
      String str1 = matcher.group(1);
      if (str1.replaceFirst("#+", "").length() == 0 || str1.replaceFirst("#+", "").matches("[\\s]+"))
         continue;
      int n = str1.length() - str1.replaceFirst("#+", "").length();
      System.out.print("<h" + n + ">" + str1.substring(n) + "</h" + n + ">");
      if(append_p == true){ System.out.print("</p>"); append_p = false;}
   }
   if(Character.isUpperCase(str.charAt(0)){
      System.out.println("<p>"+str+"</p>");
   return ("");
 }

这将测试第一个字符是否为大写字母和 append/prepend <p></p>

于 2012-10-25T06:18:38.893 回答