matheo jean
matheo jean

Reputation: 101

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.

Upvotes: 1

Views: 549

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627609

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).

Upvotes: 1

Emma
Emma

Reputation: 27763

Based on your designed expression, if I understand the question, you might just want a capturing group here,

href="([\s\S]*?)"

and replace it with url: '$1' which might work then.

Please see the demo here

Other expressions that would likely work here are:

href="([^"]+)"
href="([^"]+?)"
href="(.*)"
href="(.*?)"
href="(.+)"
href="(.+?)"

all being replaced by:

url: '$1'

Upvotes: 1

Related Questions