Regex to Find Replace Beginning and End of String
12,366
Solution 1
Find this:
/shop/(.*?)\.htm
And replace with this:
/product/\1/
Solution 2
It can be done with a single regex, try:
com\/\Kshop(\/.*?)\.htm
and replace with:
product\1/
NODE EXPLANATION
--------------------------------------------------------------------------------
com 'com'
--------------------------------------------------------------------------------
\/ '/'
--------------------------------------------------------------------------------
\K Resets the starting point of the reported match
ie: Everything that has been matched till this
point won't be changed
--------------------------------------------------------------------------------
shop 'shop'
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\/ '/'
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
htm 'htm'
To read more about regex, feel free to visit The Stack Overflow Regular Expressions FAQ
Author by
Pmaridnah
Updated on July 13, 2022Comments
-
Pmaridnah almost 2 years
My skills are very basic. I'm hoping to find a regular expression for Sublime Text 3 that finds a string by beginning and end. I'd like to keep the middle unchanged and I only want to replace the beginning and the end.
For instance. Search for url with
/shop/
at the beginning and .htm at the end. I'd then like to replace/shop/
with/product/
and replace.htm
with a forward/
e.g.
http://www.website.com/shop/ford-truck-hitch-extension.htm
becomes
http://www.website.com/product/ford-truck-hitch-extension/
This bit finds the instances but I can't figure out how to replace the beginning and end.
shop[^<]+.htm
-
secretshardul over 3 yearsIf using VS Code find-replace, use
$1
instead of\1
in/product/\1/