Search code examples
regexsublimetext3

How do I use a part of the matched text in regex for Sublime Text, in the replacement?


If I have

width: 12px 0;
width: 24px 0;

how can I use regex to replace it with

width: 12px 0px;
width: 24px 0px;

While keeping the first number intact?

I am using Sublime Text that uses Python PCRE for regex. I tried searching Google and Bing and reading the Sublime Text documentation and I couldn't find anything helpful. Using :[0-9]*px 0; and :${m}px 0px; doesn't work.


Solution

  • You could use

    (:\h*\d+px\h+\d+);
    
    • ( Capture group 1
      • :\h*\d+px Match : optional spaces and 1+ digits followed by px
      • \h+\d+ Match 1+ spaces and 1+ digits
    • ); Close group and match ;

    And replace with the first group followed by px; like $1px;

    Regex demo

    enter image description here


    Without using a capture group, this could be another option using \K to forget what is matched so far, and replace with px;

    :\h*\d+px\h+\d+\K;
    

    Regex demo