我想从下面的文本创建正则表达式匹配字符串数组。
.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() 不匹配而无法获取 array[1],并且当我使用 ^\.[\w|\W]+
而不是上面的正则表达式模式时, array[0] 包含所有内容。
我怎样才能实现这个数组?
我不坚持正则表达式,欢迎任何解决方案。
最佳答案
你已经很接近了 - 试试这个正则表达式:
^\..*?(?=(^\.|\Z))
在 Java 中,这将是“
"^\\..*?(?=(^\\.|\\Z))" // escaping the backslashes for java String.
关于java - 创建正则表达式匹配数组(多行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6774571/