如何在 Matlab 中使用正则表达式拆分带有复杂分隔符的字符串?
How to use regexp for splitting string with complex delimiter in Matlab?
我有这样一个字符串:
"%","W/m²","mm","Deg C","%","W/m²","MJ/m²","","uSec","","uSec","","uSec"
我想根据复杂的分隔符拆分它:每个项目都用连字符(左右)界定并用逗号分隔。
备注:
- 包括百分比或 2 的幂等字符,应读入。在我的示例中,我列出了 13 个项目(3 个空白)。
- 空字段(项目),也应包括(不丢弃)并替换为字符串 'unitless'
- 项目也可以包含空格("Deg C")
有人能帮帮我吗?
还有其他方法可以做到这一点,但 regexp 应该可以做到。出于速度和兼容性原因,我更喜欢 regexp('split') 而不是 strsplit。后者相对较新。
str = '"%","W/m²","mm","Deg C","%","W/m²","MJ/m²","","uSec","","uSec","","uSec"';
units = regexp(str, ',', 'split'); % split by comma
units = regexp(units, '(?<=").*(?=")', 'match', 'once'); % get content between quotes
units(cellfun(@isempty, units)) = {'unitless'}; % set empty to unitless
我有这样一个字符串:
"%","W/m²","mm","Deg C","%","W/m²","MJ/m²","","uSec","","uSec","","uSec"
我想根据复杂的分隔符拆分它:每个项目都用连字符(左右)界定并用逗号分隔。
备注:
- 包括百分比或 2 的幂等字符,应读入。在我的示例中,我列出了 13 个项目(3 个空白)。
- 空字段(项目),也应包括(不丢弃)并替换为字符串 'unitless'
- 项目也可以包含空格("Deg C")
有人能帮帮我吗?
还有其他方法可以做到这一点,但 regexp 应该可以做到。出于速度和兼容性原因,我更喜欢 regexp('split') 而不是 strsplit。后者相对较新。
str = '"%","W/m²","mm","Deg C","%","W/m²","MJ/m²","","uSec","","uSec","","uSec"';
units = regexp(str, ',', 'split'); % split by comma
units = regexp(units, '(?<=").*(?=")', 'match', 'once'); % get content between quotes
units(cellfun(@isempty, units)) = {'unitless'}; % set empty to unitless