Possible to make .* match line breaks (Replace in path)

Is there a way to get Replace in Path to work with a code block like:

<div id="id">
     <h3>Words</h3>
     <p>Indefinite length with indefinite line breaks</p>
     <p>Indefinite length with indefinite line breaks</p>
     <p>Indefinite length with indefinite line breaks</p>
</div>

If I were to do <div id="id">.*</div> it doesn't match anything. Problem being that it does't match the multiple \s within the code. Is there a way to make .* match line breaks as well?

3
9 comments

PhpStorm's regex support seems a bit limited; usually, for complex searches or replaces, I open the file in BBEdit, which I can easily do with an external script command that I set up in PhpStorm.

The bit you're missing is getting . to match newline characters. I'm not sure how this is controlled in Java's regex engine (which I believe is what PhpStorm uses), but in PCRE, this is controlled via the s pattern modifier. Looking at the help docs in PhpStorm, I see no reference to this modifier, nor any other, for that matter.

That said... It appears that PhpStorm can search across multiple lines just fine, which is a signficant limitation that some editors suffer from. In particular, I did a quick experiment and *was* able to get a multi-line pattern to work by using something other than the . character to do the match. For example, in the case of your example, this pattern works:

<div id="id">[\s\S]*</div>

Instead of looking for a . match (which won't match newlines without the appropriate pattern modifier), it looks for any character that is a whitespace character or non-whitespace character (which effectively means anything). I also did a test-replace wherein I found your sample div and replaced it with a span that had the same content. That is, these patterns:

Search: <div id="id">([\s\S]*)</div>

Replace: <span>\1</span>

Hope that helps.

7

This answer is very close! Unfortunately it's being greedy. Do you happen to know if there is another modifier to change that?

0

Just add a question mark after the star to toggle it to be non-greedy:

Search: <div id="id">([\s\S]*?)</div>

Replace: <span>\1</span>


Is that what you meant?

10

You have saved my day!

0

I tried the replace and it did not work. It populated the contents of the <span></span with a 1:

<span>1</span>

0

Ok, it's $1 not \1.

1

I landed here after a search to work out how to make the "." in a regex match newlines.

However then solved my problem using this which will match all chars including newlines:

(?:.|\n)*

Thought this was maybe worth recording here.

6

As the docs say:

PhpStorm supports all the standard regular expressions syntax

This means you can use modifiers such as `(?s)` a the start of the expression which:

makes the dot match all characters, including line breaks

FYI, IntelliJ is the same.

So your expression would become:

(?s)<div id="id">.*</div>
3

Please sign in to leave a comment.