开发者

Create array of regex match(multiline)

开发者 https://www.devze.com 2023-03-21 18:41 出处:网络
I want to create array of regex match string from the text bellow. .title1 this is a content of title1.

I want to create array of regex match string from the text bellow.

.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

and desi开发者_C百科red array is below

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"

and bellow is my code.

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());
  }
}

But with this code, array[0] contains from ".title1" to "." before ".title2", and couldn't get array[1] since m.find() doesn't match, and when I use ^\.[\w|\W]+ instead of regex pattern above, array[0] contains everything. How can I acheive this array? I don't stick to regex, any solution is welcome.


You're pretty close - try this regex instead:

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

In java, this would be"

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号