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?

7 comments
Comment actions Permalink

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.

3
Comment actions Permalink

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

0
Comment actions Permalink

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?

4
Comment actions Permalink

You have saved my day!

0
Comment actions Permalink

Thanks for sharing!!!

0
Comment actions Permalink

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

<span>1</span>

0
Comment actions Permalink

Ok, it's $1 not \1.

1

Please sign in to leave a comment.