Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Organizing Data Splitting Strings

Using strings to split strings

I want to split a string at every instance of two strings that appear within it.

In other words, if I have the string,

 "<div class="content-block">
            <div class="grid-70 tablet-grid-70 mobile-grid-70 content-meta">
              <strong>Achievement</strong>
              <h3>How Ruby Works</h3>
              <p>Ruby Basics</p>
              <div class="content-actions-container">
                <span class="icon icon-complete"></span>
                <strong>Achieved</strong>
                <p>Mar 18, 2015</p>
              </div>
            </div>"

and, I want to split at every instance of

"</strong>
                <p>"

and

"</strong>
              <h3>"

How do I do that?

2 Answers

We always learn from our mistakes :)

Seem like you want to split the input text on </strong> followed by a zero or more space characters such as newline, tab, blanks and then either a <p> tag or an <h3> tag.

I think the code below might help. The regex pattern for splitting the input string consists of the HTML tag literal "</strong>" followed by the escaped character class \s (space characters) with the * quantifier (zero or more instances of preceding token) followed by either a <p> or a <h3> HTML literal.

String strpattern = "</strong>\\s*(<p>|<h3>)";
        Pattern objPattern = Pattern.compile(strpattern);
        String[] arMatches = objPattern.split(txtinput);

        if (arMatches.length != 0 ) {
            int matchcount = 0;
           System.out.println("arMatches.length = " + arMatches.length);
           for (String element : arMatches) {
               System.out.println("Match #" + matchcount);
               System.out.println(element + "\n\n\n");
               matchcount++;
           }//for
        } else {
            System.out.println("Could not split input.");
        }//if 

Below are the results I obtained:

arMatches.length = 3
Match #0
<div class="content-block">
<div class="grid-70 tablet-grid-70 mobile-grid-70 content-meta">
<strong>Achievement



Match #1
How Ruby Works</h3>
<p>Ruby Basics</p>
<div class="content-actions-container">
<span class="icon icon-complete"></span>
<strong>Achieved



Match #2
Mar 18, 2015</p>
</div>
</div>