Tip: search for a string that spans multiple lines

The searching tip presented afterwards applies to any application that allows you to use regular expressions when finding strings within a file such as PyCharm:

PyCharm allows you to search your source code with regex

Let's say we want to search for the string "turned into a democracy" in the following text:
The difficulty is that sometimes the string spans multiple lines and you want to match it no matter where the newline(s) happens in the string.

If we use the simple search query without tokens "turned into a democracy", we will only match the first occurrence of the given string, as shown in the following regex101.com demo:


To match all occurrences of the string no matter how many lines it spans, the following regex will do the trick: "turned\s+into\s+a\s+democracy". We replaced the spaces between the words with whitespaces (one or unlimited), as shown in the following regex101.com demo:

You can also try it out with PyCharm or any other application that allows regex-based search:

Reference

This blog post is based on search-ebooks README (personal project I'm working on for searching ebook contents and metadata of various formats).

Comments

Popular posts from this blog

Install the MAMP (Mac, Apache, MySQL, PHP) stack

Deactivate conda's base environment on startup

Product review: SMONET wireless security camera system