如何在MATLAB中从字符串创建首字母缩略词?

Ali*_*Ali 3 regex string matlab acronym

有没有一种简单的方法可以在MATLAB中从字符串创建首字母缩略词?例如:

'Superior Temporal Gyrus' => 'STG'
Run Code Online (Sandbox Code Playgroud)

gno*_*ice 8

如果你想把每个大写字母都写成缩写......

...你可以使用函数REGEXP:

str = 'Superior Temporal Gyrus';  %# Sample string
abbr = str(regexp(str,'[A-Z]'));  %# Get all capital letters
Run Code Online (Sandbox Code Playgroud)

...或者你可以使用UPPERISSPACE函数:

abbr = str((str == upper(str)) & ~isspace(str));  %# Compare str to its uppercase
                                                  %#   version and keep elements
                                                  %#   that match, ignoring
                                                  %#   whitespace
Run Code Online (Sandbox Code Playgroud)

...或者您可以使用大写字母的ASCII/UNICODE值:

abbr = str((str <= 90) & (str >= 65));  %# Get capital letters A (65) to Z (90)
Run Code Online (Sandbox Code Playgroud)


如果你想把每个开始单词的字母都放到缩写中......

...你可以使用函数REGEXP:

abbr = str(regexp(str,'\w+'));  %# Get the starting letter of each word
Run Code Online (Sandbox Code Playgroud)

...或者您可以使用STRTRIM,FINDISSPACE函数:

str = strtrim(str);  %# Trim leading and trailing whitespace first
abbr = str([1 find(isspace(str))+1]);  %# Get the first element of str and every
                                       %#   element following whitespace
Run Code Online (Sandbox Code Playgroud)

...或者您可以使用逻辑索引修改上述内容以避免调用FIND:

str = strtrim(str);  %# Still have to trim whitespace
abbr = str([true isspace(str)]);
Run Code Online (Sandbox Code Playgroud)


如果你想把每个开头一个单词的大写字母都放到一个缩写中......

...你可以使用REGEXP函数:

abbr = str(regexp(str,'\<[A-Z]\w*'));
Run Code Online (Sandbox Code Playgroud)