簡體   English   中英

降價算法:字符串困難

[英]Markdown algorithm: string difficulties

我開始編寫此算法:

public static String convert(String str) {
    if (str.equals("# "))
        return " ";

    if (str.matches("#+.+")) {
        int n = str.length() - str.replaceFirst("#+", "").length();
        return "<h" + n + ">" + str.substring(n) + "<h" + n + ">";
    }

    return str;
}
}

因此,當我鍵入#### title時,它將返回<h4> title </ h4>

我的問題是,當我寫#### title ### title時,我希望它返回<h4> title </ h4> <h3> title </ h3>,但它只返回<h4> title </ h4 > ...我在做什么錯???

那是因為您使用的是模式:- #+.+

現在,因為. 匹配正則表達式中的所有內容,因此在上述模式中,它匹配initial set #'s之后的everything

因此,對於您的輸入:- #### title ### title ,您的模式將匹配:-

  • #+將匹配####
  • .+將匹配title###title

您需要將正則表達式更改為:- (#+[^#]+) ,並且可能需要在此處使用Pattern類來獲取所需的輸出,因為您希望將字符串的every部分都與給定的pattern匹配。

#+[^#]+ ->將匹配第一組# ,然后匹配除#之外的所有內容。 因此它停止了下一組#'s開始。

使用方法如下:-

    String str = "####title###title";  // str is the method parameter
    if (str.equals("# "))
        System.out.println(" ");

    Pattern pattern = Pattern.compile("(#+[^#]+)");
    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        String str1 = matcher.group(1);
        int n = str1.length() - str1.replaceFirst("#+", "").length();
        System.out.println("<h" + n + ">" + str1.substring(n) + "</h" + n + ">");
    }

輸出 :-

<h4>title</h4>
<h3>title</h3>

您只替換第一次出現的#+。 嘗試將if替換為一會兒,而不是在if內部返回,而是將結果附加到StringBuilder中。
就像是:

String str = "####title###title2"; 
    StringBuilder sb = new StringBuilder();
    while (str.matches("#+.+")) {          
        int n = str.length() - str.replaceFirst("#+", "").length();
         str = str.replaceFirst("#+", "");
        int y = str.length();
        if(str.matches(".+#+.+")) {
            y = str.indexOf("#");
            sb.append( "<h" + n + ">" + str.substring(0,y) + "<h" + n + ">");
            str = str.substring(y, str.length());
        } else {
            sb.append( "<h" + n + ">" + str.substring(0,y) + "<h" + n + ">");
        }

    }
    System.out.println(sb.toString());

}

您匹配了錯誤的字符串,請嘗試以下方法:

#+[^#]+

當然,您要遞歸或循環調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM