簡體   English   中英

使用Java中的正則表達式獲取字符串的子字符串

[英]Get substring of a string using regular expression in Java

我在使用Java中的正則表達式從字符串中提取子字符串時遇到問題。 例如,我有以下一串字符串。

===Albedo–temperature feedback===
When an area's albedo changes due to snowfall, a snow–temperature [[feedback]] results. 

===Snow===
Snow albedo is highly variable, ranging from as high as 0.9 for freshly fallen snow, to about 0.4 for melting snow, and as low as 0.2 for dirty snow.

====Small-scale effects====
Albedo works on a smaller scale, too.

請注意 ,整個內容都是字符串。

這里===之間顯示的每個元素都是節標題 ,我想提取每個節內容及其標題(標題)。

所以,我試圖生成的輸出如下所示。

1. Albedo–temperature feedback
content: When an area's albedo changes due to snowfall, a snow–temperature [[feedback]] results.

2. Snow
content: Snow albedo is highly variable, ranging from as high as 0.9 for freshly fallen snow, to about 0.4 for melting snow, and as low as 0.2 for dirty snow.

2. Small-scale effects
content: Albedo works on a smaller scale, too.

我使用以下模式定義來提取標頭。

Pattern pattern = Pattern.compile("[=]{2,5}(.*?)[=]{2,5}");

這給了我, Albedo–temperature feedbackSnowSmall-scale effects

現在我想要的是每個節標題之間的內容。 我無法提取它們。 任何幫助,將不勝感激。

嘗試這個。

String s = ""
    + "===Albedo–temperature feedback===\n"
    + "When an area's albedo changes due to snowfall, a snow–temperature [[feedback]] results. \n"
    + "\n"
    + "===Snow===\n"
    + "Snow albedo is highly variable, ranging from as high as 0.9 for freshly fallen snow, to about 0.4 for melting snow, and as low as 0.2 for dirty snow.\n"
    + "\n"
    + "====Small-scale effects====\n"
    + "Albedo works on a smaller scale, too.\n";
Pattern PAT = Pattern.compile("^()$|^={2,5}(.+?)={2,5}$|^(.+)$", Pattern.MULTILINE);
String NEWLINE = "\n";
Matcher m = PAT.matcher(s);
int number = 0;
StringBuilder sb = new StringBuilder();
while (m.find()) {
    if (m.group(2) != null)
        sb.append(++number).append(". ").append(m.group(2));
    else if (m.group(3) != null)
        sb.append("content: ").append(m.group(3));
    sb.append(NEWLINE);
}
System.out.println(sb.toString());

暫無
暫無

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

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