File Exchange

image thumbnail

Find and replace in selection

version 1.1.0.0 (1.5 KB) by Sam Johnson
Find and replace in currently selected editor text.

8 Downloads

Updated 21 Sep 2012

View Version History

View License

Uses the MATLAB Editor API and STRREP to find and replace all occurrences of a substring within the currently selected editor text.

Cite As

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 .

Comments and Ratings (14)

Sinan Islam

Hao Yin

Pablo López

Great!

Eric

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.

Meng

Anthony

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

Anthony

Anthony

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

Alessandro Masullo

I love you!

Alina

Sam,
it worked now, many thanks.

Sam Johnson

Hi Alina,

you need to pass strings to the function.

i.e: replaceInSelection('median', 'skew')

Alina

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

Sam Johnson

Sadly there is no associated GUI - you select a region of text in the editor and call the function from the command window.

Joseph Cullen

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?

thanks

MATLAB Release Compatibility
Created with R2012a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!