Okay then.
First, if you want to allow for variable pre/post you can do this like this:
Code: Select all
$pre = '<pre>'
$post = '<post>'
Find And Replace '^.+?\t\d+', $pre &'\0' & $post, 'Ea'
Now let's consider how we can do find/replace in the macro language. Find and Replace is an operation on text, so you need a text object. For the document as a whole this would be:
Code: Select all
$doc.text.findAndReplace '^.+?\t\d+', $pre &'\0' & $post, 'Ea'
So what is the difference?
The most obvious difference is if you catch the result in a variable ($result = …), then the command style will result in an integer matching the number of replacements, while the macro command will return an array of
text selection objects.
Now you want to do some more complex calculation on the string before doing the replace. In that case you can do the find/replace in two steps. Since the macro command returns a text selection object we can use that to do the replace:
Code: Select all
$result = $doc.text.find '^.+?\t\d+', 'E'
$result.text.replaceInRange $result.range, $pre & $result.subtext & $post
Since
$result is a text selection object it contains all the bits we need: $result.text is the original text object where we did the find, the $result.range is the location where we want to replace, and $result.subtext is a copy of the part of the main text that matches the find expression.
Now note that in this example I did this for only one instance. If you want to do this for all instances you will need to put this in a loop as in your original code,
but there is an important point to note. The code works with ranges. And ranges are simple numbers that count from the beginning of the file. If you change the file, then any range after the change is likely to be 'off'. So to avoid any problems you will want to work from back-to-front. So the loop for the above code becomes:
Code: Select all
$results = $doc.text.find '^.+?\t\d+', 'Ea'
foreach $result in reversed $results
$result.text.replaceInRange $result.range, $pre & $result.subtext & $post
end
Here I changed the options to 'Ea' to find all, and then I catch the
$results (plural). Then I loop through them in reverse.
So that's the basic approach.