Multi-Line Regex Searches in PhpStorm

Searching for regex patterns across multiple lines

This is a quick tip about doing multi-line regular expression (regex) searches in PhpStorm. Even if you don't use PhpStorm, you might find this helpful if your editor can do regex searches but by default won't do multi-line searches.

The Problem

Sometimes, you want to use a regular expression that searches for text that might be on more than one line. Without a multi-line search, there's no way to do it. When you do a regex search in code, you can set it to do a multi-line search with a modifier at the end of the patterh. This is no help, though, when you want to do the search in your editor and there's no easy way to tell it to include line breaks in the pattern.

There may be a way to tell PhpStorm's editor to do a multi-line search, but if there is, I haven't found it.

The Solution

The answer is to use a character class that will cover any end of line character. The easiest pattern for that is [\s\S]. This will include any space character, and any non-space character. In other words, any character at all, including newlines.

Say, for example, that you want to find the strings string1 and string2 in a file but the two strings may not be on the same line. You can use this pattern:


The question mark after [\s\S]+ makes the search "non-greedy," so it will stop at the first match. If you want all the text between the first occurrence of string1 and the *last* occurrence of string2, you can remove it.

Comments (0)

Please login to comment.