Uses the MATLAB Editor API and STRREP to find and replace all occurrences of a substring within the currently selected editor text.
Sam Johnson (2021). Find and replace in selection (https://www.mathworks.com/matlabcentral/fileexchange/38264-find-and-replace-in-selection), MATLAB Central File Exchange. Retrieved .
One can easily modify this to fit within a shortcut on the Quick Access Toolbar. That seems preferable to a function.
Also, one must be *really* careful with this. If you have "there" in a string and tell the function to replace "here" with "here1", "there" becomes "there1". That could be problematic.
To solve the issue I raised in my last comment, you can simply:
- add the line: numberOfReplacements = numel(strfind(newText(startPos:endPos-1), oldSubstr));
before the line with strrep.
- change the penultimate line for:
[selectionPosition(3) selectionPosition(4)] = matlab.desktop.editor.indexToPositionInLine(activeEditor, endPos+numberOfReplacements*(numel(newSubstr)-numel(oldSubstr)));
Excellent! Thanks a lot!
I only have a little comment:
if you replace an expression by a longer expression (e. g. '*' by '.*') part of the selected text is deselected (the number of selected characters remains constant).
It can cause problems if you have to perform several replacements.
It could probably be solved by:
- making the difference (D) of the replacing expression length and the replaced expression length
- extending the selection after replacement of (number of replacement)*D
Anyway thanks a lot for your submission, it's really great :-)
I love you!
it worked now, many thanks.
you need to pass strings to the function.
i.e: replaceInSelection('median', 'skew')
I tried it but I keep getting this error:
EDU>> replaceInSelection(median, skew)
Error using median (line 27)
Not enough input arguments.
I selected the text in editor then typed replaceInSelection(median, skew) in the command window.
Sadly there is no associated GUI - you select a region of text in the editor and call the function from the command window.
How do you use this in practic? With a function call from the command window? Or is there an associated GUI?
If so how do you call it up?
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!