DEV Community

Ted M. Young
Ted M. Young

Posted on • Updated on

Live Coding Learnings - June 18, 2019

Summary of what I learned in today's live coding stream at https://twitch.tv/jitterted.

Matching newlines in RegEx

For the text I'm working with, I want regex search and replace to work across newlines (by default matching stops at a new line). Today I learned that I need to pre-pend this: (?s) to the regex String, which turns on DOTALL mode and therefore the dot wildcard will match across new lines. For details, see the JavaDoc: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#DOTALL

Example of matches() using DOTALL

I want to search for text that's surrounded by 3 equal signs (===)
both at the beginning and at the end. The text can span multiple lines.

For example:

Before text.
===
Text inside the equals signs.
===
Outside text.

To search for the text, I would use the String.matches() method, like this:

boolean found = text.matches("(?s)===(.*?)===");

Which returns true if the pattern is found, as it would be in the
above example.

Example of replaceAll using DOTALL

If I want to replace the triple backtick code block with a <pre> tag (as I do in my live stream), then I'd do this:

Which would output this:

<pre>
public class Stock {

}
</pre>

Scanner for Parsing

I used Scanner in a few places and forgot about it until I was reminded by one of my regular stream viewers (thanks flamaddidle84!). Today, I wanted to parse some text and split the lines whenever there was an empty line between two non-empty lines.

For example, given this text:

Block one.
Still part of block one.
Yep, still part of block one.

Block two here.
Still part of block two.

Last block here.

I want to end up with three pieces of text. Using the Scanner class and the fact that the delimiter can be specified, this is all I needed:

Scanner scanner = new Scanner(text).useDelimiter("\n\n");

Then, all I had to do was use the scanner.tokens() method (only available starting in Java 9) to give me a stream of these blocks, e.g.:

scanner.tokens()
       .map(s -> "<p>" + s + "</p>\n")
       .collect(Collectors.toList());

Which uses replaceAll on each block to surround it with the HTML <p> (paragraph) tag. Here's a full code example:

When run, it results in this output:

<p>Block one.
Still part of block one.
Yep, still part of block one.</p>

<p>Block two here.
Still part of block two.</p>

<p>Last block here.
</p>

Watch Me Live Code on Twitch

If you want to see how I use TDD to code in Java and Spring, and learn with me, tune in to my daily stream at Twitch.TV/JitterTed. I'm usually streaming from 12pm PDT (1900 UTC) for around 3 hours. You can also chat with me on my Discord.

Top comments (0)