簡體   English   中英

創建正則表達式匹配數組(多行)

[英]Create array of regex match(multiline)

我想從下面的文本中創建正則表達式匹配字符串數組。

.title1
this is a content of title1.
this is also a content of title1.
..title2
this is a content of title2
this is also a content of title2

所需的數組在下面

array[0] = ".title1
this is a content of title1.
this is also a content of title1."

array[1] = "..title2
this is a content of title2
this is also a content of title2"

下面是我的代碼。

ArrayList<String> array = new ArrayList<String>();
Pattern p = Pattern.compile("^\.[\w|\W]+^\.", Pattern.MULTILINE);
Matcher m = p.matcher(textAbove);

if(m.matches()){
  m.reset();
  while(m.find()){
    array.add(m.group());
  }
}

但是使用此代碼,array[0] 包含從“.title1”到“。” 在“.title2”之前,並且由於 m.find() 不匹配而無法獲取數組 [1],並且當我使用^\.[\w|\W]+而不是上面的正則表達式模式時,數組 [0 ] 包含一切。 我怎樣才能實現這個數組? 我不堅持正則表達式,歡迎任何解決方案。

你非常接近 - 試試這個正則表達式:

^\..*?(?=(^\.|\Z))

在 java 中,這將是“

"^\\..*?(?=(^\\.|\\Z))" // escaping the backslashes for java String.

暫無
暫無

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

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