How to escape a portion of a string in regular expressions
Show older comments
Hello,
i want to dynamically create a regular expression from an input string. However i only want a small subset of expressions to be treated as such. Most of the input shall be treated as literal (e.g. dots '.' shall actually be treated as dots and not wildcards)
Is there a way to escape a whole group/substring when defining a regexp, or is the only way to escape all special chars, except the ones i want to keep, manually. If i need to escape everything manually, is there a syntax/keyword which gets me all special chars in the string so i can escape all of them?
Example (dots shall be treated as literal dots):
>> r = myfun('a.b.c','a.b.')
r = 1
>> r_myfun('aXb.c','a.b.')
r = []
4 Comments
I think that would be the best solution: find all special characters and escape them. Be careful with how you implement that. A list of strreps would have side effects:
str='a.b';
str=strrep(str,'.','\.');
str=strrep(str,'\','\\');
str
Max Heimann
on 21 Mar 2022
Walter Roberson
on 21 Mar 2022
Perhaps the newer "pattern" facilities would help?
Max Heimann
on 21 Mar 2022
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!