1

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 desired 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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
yshrsmz
  • 1,179
  • 2
  • 15
  • 33

1 Answers1

1

You're pretty close - try this regex instead:

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

In java, this would be"

"^\\..*?(?=(^\\.|\\Z))" // escaping the backslashes for java String.
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    Hi, thank you for the answer. I tested your regex with RegexPlanet( http://www.regexplanet.com/simple/index.html ), but it didn't match at all... what – yshrsmz Jul 21 '11 at 13:01
  • Sorry, It matched, but array[0] contains everything. what happened? :( – yshrsmz Jul 21 '11 at 13:04
  • oops - i made it a greedy match. I have edited it to include the `?` - making it non-greedy. Try it now – Bohemian Jul 21 '11 at 13:14