I'm looking to search a String for a given value and then, if this value is found (anywhere in the string), I want to replace the entire string with a new one. Is this possible with regexprep?
5 views (last 30 days)
Show older comments
As previously stated, I'm looking to search a string for a given value. If this value is present in the string, anywhere at all, I want to replace this entire string with an new one. I've spent about an hour trying to accomplish this with regexprep, but regexprep only seems to allow me to replace the portion of the string I'm searching for with a new string.
For example, I have a variable with a string value of the alphabet here:
String = abcde+fghijklm+nopq+rstuvwxyz
I want to search this string and make sure there aren't any random '+' signs in there to throw off my groove. If there are, I want to replace the entire string with the actual alphabet, without the random plus signs in there. I can search this string for a '+' using regexprep like this
String= regexprep(String,'+','abcdefghijklmnopqrstuvwxyz')
but this method will replace only the plus sign with the alphabet, leaving me with an alphabet inside an alphabet. I want it to replace the entire incorret string with a the new, correct one. Is there any way to do this using regexprep? Or any other method?
My end goal is to search a string for a given value, and then, if found, replace the entire string with a new one. I appreciate any help.
2 Comments
Accepted Answer
Walter Roberson
on 16 Jul 2015
regexprep(String, '.*\+.*', 'a':'z')
If there are no matches because there is no + then the replacement is not done, leaving everything intact.
3 Comments
Walter Roberson
on 16 Jul 2015
regexprep(String, '.*[-+*/][-+*/]+.*', 'error: multiple operators in a row')
However you need to consider your handling of negative numbers, as 3+-5 is usually considered to be (3)+(-5) which is valid if you have negative numbers.
If you wish the input string +5 to be valid as representing positive 5 then that means you are wanting to support "unary plus", in which case 3++8 would be parsed as (3)+(+8) which would be valid.
If you support negative numbers then any of your operators can be followed by - such as in 8/-2 . If you support unary plus as well then any of your operators can be followed by + such as in 8/+2 .
More Answers (1)
Azzi Abdelmalek
on 15 Jul 2015
Edited: Azzi Abdelmalek
on 15 Jul 2015
What you want is to replace a '+' by a blank
String = 'abcdefghijklmnop+qrstuvwxyz'
String= regexprep(String,'+','')
or
String= strrep(String,'+','')
2 Comments
Azzi Abdelmalek
on 16 Jul 2015
Samuel, please edit your original question, try to be brief and clear. You can illustrate with an example, post the expected result.
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!