Important: Use the ( )
parentheses in your search string
While the previous answer is correct there is an important thing to emphasize! All the matched segments in your search string that you want to use in your replacement string must be enclosed by ( )
parentheses, otherwise these matched segments won't be accessible to defined variables such as $1
, $2
or \1
, \2
etc.
For example we want to replace 'em' with 'px' but preserve the digit values:
margin: 10em; /* Expected: margin: 10px */
margin: 2em; /* Expected: margin: 2px */
- Replacement string:
margin: $1px
or margin: \1px
- Search string (CORRECT):
margin: ([0-9]*)em
// with parentheses
- Search string (INCORRECT):
margin: [0-9]*em
CORRECT CASE EXAMPLE: Using margin: ([0-9]*)em
search string (with parentheses). Enclose the desired matched segment (e.g. $1
or \1
) by ( )
parentheses as following:
- Find:
margin: ([0-9]*)em
(with parentheses)
- Replace to:
margin: $1px
or margin: \1px
- Result:
margin: 10px;
margin: 2px;
INCORRECT CASE EXAMPLE: Using margin: [0-9]*em
search string (without parentheses). The following regex pattern will match the desired lines but matched segments will not be available in replaced string as variables such as $1
or \1
:
- Find:
margin: [0-9]*em
(without parentheses)
- Replace to:
margin: $1px
or margin: \1px
- Result:
margin: px; /* `$1` is undefined */
margin: px; /* `$1` is undefined */