-1

Consider the text structure

 (Title)[#1Title-link]
      (Chapter1)[#Chapter1-link]
      (Chapter2)[#Chapter2-link]
      (Chapter3)[#Chapter3-link]

How can i backrefence to [#Title-link] without matching it on find result. Im trying to change

      (Chapter1)[#Chapter1-link] => (Chapter1)[#1Title-link-Chapter1-link]
      (Chapter2)[#Chapter2-link] => (Chapter2)[#1Title-link-Chapter2-link]
      (Chapter3)[#Chapter3-link] => (Chapter3)[#1Title-link-Chapter3-link]

I tried to use and find

(\(Title\)\[(.*?)])([\s\S]*?\[)#(\D.*?\])

then replace it with

$1$3$2-$4

but the problem in here it only highlight once per find and i got lots of chapter its too inefficient to replace it one by one. Making a constant title is no good too because i have multiple files with that same structure.

Is this possible in regex? any solution or alternative is welcome.

rinze
  • 1
  • 1

1 Answers1

0

You can first do a search to get the correct substitution string and then do a subsequent replace operation with that substitution string. You did not specify what language you were using, so here is the code in Python (where that back reference to group 1 is \1 rather than the more usual $1):

import re

text = """(Title)[#1Title-link]
      (Chapter1)[#Chapter1-link]
      (Chapter2)[#Chapter2-link]
      (Chapter3)[#Chapter3-link]"""

m = re.search(r'(?:\(Title\)\[#([^\]]*)\])', text)
assert(m) # that we have a match
substitution = m.group(1)
text = re.sub(r'\[#Chapter([^\]]*)\]', r'[#' + substitution + r'-Chapter\1' + ']', text)
print(text)

Prints:

(Title)[#1Title-link]
      (Chapter1)[#1Title-link-Chapter1-link]
      (Chapter2)[#1Title-link-Chapter2-link]
      (Chapter3)[#1Title-link-Chapter3-link]

See Regex Demo 1 for getting the substitution string

See Regex Demo 2 for making the subsitutions

Booboo
  • 38,656
  • 3
  • 37
  • 60