Characters, Text and Regular Expressions

A text in single quotes, 'VCU', is a character vector: a 1×n array of char.

Concept

A text in single quotes, 'VCU', is a character vector: a 1×n array of char. Everything you know about arrays applies: name(1:3), length(name), [a b] to concatenate, upper, lower, fliplr. To include a quote, double it: 'it''s'.

Comparisons: use strcmp/strcmpi (whole text), not == (which compares character by character and needs equal lengths).

[a b], strcat, sprintf, num2str, mat2str Compare / search

strcmp, strcmpi, strncmp, strfind, ismember strsplit, strjoin

strtrim, upper, lower, strrep, deblank str2double, num2str, dec2bin, bin2dec, dec2hex, hex2dec regexp, regexpi, regexprep

Lists of texts of different lengths are stored in cell arrays of character vectors: {'VCU', 'BMS', 'Gateway'} (Module 14).

String Arrays (MATLAB R2016b+) MATLAB also has a string class created with double quotes: "VCU". String arrays support + for concatenation, == comparison, and functions like contains, startsWith, split, join. *MATLAB only — Octave treats double quotes as a character vector with escape sequences, so this course's verified examples use character vectors.*

% MATLAB only - not run in this course
names = ["VCU" "BMS" "GW"];
full = names + "_ECU";                 % ["VCU_ECU" "BMS_ECU" "GW_ECU"]
tf = contains(names, "B");             % [false true false]

Why It Matters

Log files, file names, CAN IDs in hex, test reports and user input are all text. Regular expressions extract data from unstructured text in one line.

Syntax

s = sprintf('%s_%03d', 'LOG', 7);           % 'LOG_007'
parts = strsplit('a,b,c', ',');             % {'a','b','c'}
tok = regexp(str, 'sw=(\d+)', 'tokens');
tf = strcmp(a, b);

Example

8.1 Working with text

name = 'Battery Management System';
fprintf('length %d, first 7 chars "%s", upper "%s"\n', length(name), name(1:7), upper(name))
code = 'BMS';
full = [code ' v' num2str(1.9)];                     % concatenate char vectors
disp(full)
fprintf('strcat: "%s", sprintf: "%s"\n', strcat('ECU', '-', 'VCU'), sprintf('%s_%03d', 'LOG', 7))
fprintf('strcmp(''abc'', ''abc'') = %d, strcmpi(''ABC'', ''abc'') = %d, ''abc'' == ''abd'' -> %s\n', ...
        strcmp('abc', 'abc'), strcmpi('ABC', 'abc'), mat2str('abc' == 'abd'))
line = 'P0A80,U0100,C1234';
parts = strsplit(line, ',');
fprintf('strsplit gives %d parts; second is %s\n', numel(parts), parts{2})
fprintf('strjoin: %s\n', strjoin(parts, ' | '))
fprintf('strrep: %s\n', strrep(line, ',', ';'))
fprintf('strfind(line, ''U'') = %d, contains-like test: %d\n', strfind(line, 'U'), ~isempty(strfind(line, 'C12')))
fprintf('strtrim("  padded  ") = "%s"\n', strtrim('  padded  '))
fprintf('num2str(pi, 8) = %s, str2double(''12.5'') + 1 = %g, str2double(''abc'') = %g\n', num2str(pi, 8), str2double('12.5') + 1, str2double('abc'))
tok = regexp('VCU sw=2.4.1', 'sw=(\d+)\.(\d+)\.(\d+)', 'tokens');
fprintf('regexp tokens: major %s, minor %s, patch %s\n', tok{1
…

Expected Result

'abc' == 'abd' compared character by character ([true true false]), while strcmp compares whole texts. str2double returns NaN for invalid input instead of raising an error.

length 25, first 7 chars "Battery", upper "BATTERY MANAGEMENT SYSTEM"
BMS v1.9
strcat: "ECU-VCU", sprintf: "LOG_007"
strcmp('abc', 'abc') = 1, strcmpi('ABC', 'abc') = 1, 'abc' == 'abd' -> [true true false]
strsplit gives 3 parts; second is U0100
strjoin: P0A80 | U0100 | C1234
strrep: P0A80;U0100;C1234
strfind(line, 'U') = 7, contains-like test: 1
strtrim("  padded  ") = "padded"
num2str(pi, 8) = 3.1415927, str2double('12.5') + 1 = 13.5, str2double('abc') = NaN
regexp tokens: major 2, minor 4, patch 1
regexprep: speed:120 rpm:800
dec2bin(10) = 1010, dec2hex(255) = FF, hex2dec('7E0') = 2016

Common Mistakes

if name == 'VCU' with texts of different length (error) — use strcmp.

strcat removes trailing spaces of character arrays; use [a b] or sprintf when spaces matter.

num2str precision surprises (default 4 significant digits after the point for non-integers — use sprintf/num2str(x, precision)).

str2num evaluates its input as code (unsafe); prefer str2double.

Best Practices

Use sprintf for all formatted text.

Store lists of names in cell arrays (or string arrays in modern MATLAB).

Validate numeric text with str2double + isnan.

Interview Relevance

Medium: "char array vs string?", "how do you compare strings?", "how do you split a comma-separated line?", "how do you extract numbers with a regular expression?".

Practice Questions

Reverse a word and check whether it is a palindrome.

Count the vowels in a sentence.

Parse '2026-09-30 08:15:02' into year, month, day, hour, minute and second.

Replace every run of spaces in a text with a single space using regexprep.

Quick Quiz

Q1. (Multiple choice) Which compares two texts of possibly different lengths? A) a == b B) strcmp(a, b) C) isequal(a == b) D) a = b Answer: B.

Q2. (Predict the output) str2double('abc') Answer: NaN (verified).

Q3. (True/False) 'abc' == 'abd' returns a single logical value.

Answer: False. It returns [1 1 0] (verified).

Q4. (Find the bug) name = 'Bench' + '01'; Answer: + adds character codes numerically; concatenate with ['Bench' '01'] or sprintf.

Coding Challenge

Parse the log line 't=12.5 id=18FEF100 dlc=8' with regexp named tokens and print the time as a number, the ID in decimal and the DLC.

line = 't=12.5 id=18FEF100 dlc=8';
s = regexp(line, 't=(?<t>[\d.]+) id=(?<id>[0-9A-F]+) dlc=(?<dlc>\d)', 'names');
fprintf('time %.1f s, id %d (0x%s), dlc %d\n', str2double(s.t), hex2dec(s.id), s.id, str2double(s.dlc))