MATLAB: How to compare two strings, ignoring any white space or punctuation characters


I would like to compare two strings. The strings may have varying numbers of spaces and punctuation characters (not necessarily at the beginning or end of the string), which I would like to ignore.

Best Answer

You can use regular expressions to remove the characters from the strings that you would like to ignore in the comparison. You can then use the modified strings to perform the comparison.
The following example illustrates how you can use regular expressions to remove white space and punctuation characters from a string. The REGEXP function is used to match the regular expression:
a = 'test';
b = 'te s.t';
%Create a regular expression
%This expression matches any character except a whitespace, comma, period, semicolon, or colon
exp = '[^ \f\n\r\t\v.,;:]*';
%Find the matches within the string
b1 = regexp(b, exp, 'match');
%Concatenate all matches into a single string
b1 = [b1{:}];
%Repeat above for the other string
a1 = regexp(a, exp, 'match');
a1 = [a1{:}];
%Compare the modified strings
match = strcmp(a1, b1)
To learn more about creating regular expressions and using the REGEXP function, please see the following documentation pages:
>>web(fullfile(docroot, 'matlab/ref/regexp.html'))