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.

1 Answer 1

1

You're pretty close - try this regex instead:

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

In java, this would be"

"^\\..*?(?=(^\\.|\\Z))" // escaping the backslashes for java String.
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thank you for the answer. I tested your regex with RegexPlanet( regexplanet.com/simple/index.html ), but it didn't match at all... what
Sorry, It matched, but array[0] contains everything. what happened? :(
oops - i made it a greedy match. I have edited it to include the ? - making it non-greedy. Try it now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.