How to erase a substring that starts with a given pattern?
Show older comments
ERRATUM: c consists of character vectors, not strings.
c = {'Glucose C6H12O6'; 'Benzol C6H6'}
Hello,
Assume we have a cell array with string variables:
c = {"Glucose C6H12O6"; "Benzol C6H6"}
The goal is to remove chemical formulas from the strings and to get
c = {"Glucose"; "Benzol"}
The names can also be longer than one word. My idea for now is to define a pattern
pat = " C" + digitsPattern + "H" + digitsPattern;
and then to remove everything starting from that pattern till the end. I try to use the function eraseBetween, which can delete a substring between either two patterns or two positions. But my start point is a pattern, and end point - a position. So my questions are:
- Is there a way to flag the end of the string as a pattern that will be unique for the given string?
- How to find the starting position of a pattern in a string? We assume that there is only one pattern in each string.
A workaround is to add a unique pattern to the end of the string, and then delete everything between the two patterns (including them), but it is not ideal since I cannot be 100% sure the unique pattern is really unique.
Thank you in advance.
4 Comments
If you had a propoer string array then this would be much easier:
c = ["Glucose C6H12O6"; "Benzol C6H6"]
d = regexprep(c,'\s*(\w\d+)+','')
or even just get the data that you want:
d = regexp(c,'^\w+','once','match')
See "Why Do Strings in Cell Arrays Return an Error?" here:
Wassili Dimitriew
on 22 Sep 2026 at 11:40
Edited: Wassili Dimitriew
on 22 Sep 2026 at 11:52
Simpler than patterns and STRIP and all that jazz:
c = {'Trans 4 Hydroxy L proline C5H9NO3'};
d = regexprep(c,'\s*(\w+\d+)+','')
dpb
on 23 Sep 2026 at 17:02
Yeah, assuming one can figure out the regex pattern... :>)
Accepted Answer
More Answers (0)
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!