Search code examples
htmlregexsublimetext3

How to modify links in multiple files with regex in Sublime Text 3


I need to copy the URL of a specific tag within more than 500 HTML files where the URLs are random, and put it in another but preserving all code. That is, copy the link inside the quotation marks of a href tag and repeat it in another tag.

For example I want to change this:

href="PODCAST_32_LINK" 
url: 'RANDOM_PODCAST_LINK'

to:

href="PODCAST_32_LINK"
url: 'PODCAST_32_LINK'

I can capture the link with the regex [\S\s]*? using the Find function, but I'm not sure what I can put in the Replace field.

I tried:

Find: href="[\S\s]*?"
Replace: url:'$1'

However, of course, this breaks the code, replacing the first with the second.


Solution

  • You may use

    Find What:      (?s)(href="([^"]+)".*?url: ')[^']*
    Replace With: $1$2

    See the regex demo

    Details

    • (?s) - . now matches any char including line break chars
    • (href="([^"]+)".*?url: ') - Group 1:
      • href=" - a literal substring
      • ([^"]+) - Group 2: 1+ chars other than "
      • " - a " char
      • .*? - any 0+ chars, as few as possible
      • url: ' - a literal substring.
    • [^']* - 0 or more chars other than '.

    The replacement is the concatenation of values in Group 1 (from href till url: ') and 2 (the href contents).