【问题标题】:Find substring with certain pattern anywhere in a string在字符串中的任意位置查找具有特定模式的子字符串
【发布时间】:2020-05-13 09:11:39
【问题描述】:

我从我们的设备(数组)中得到了很多字符串。有两种不同的字符串:

  1. 011_c_srr_Rtzfi_at000_hh5_fs_v343_l067_i1_Test_Test
  2. 041_c_ddr_Rtzfi_ds000_hh5_fs_v343_l037_i1_Test_hall(需要的信息在字符串中间)
  3. 061_t_err_Rsas_au000_ti3_fs_v777_l011_ *
  4. 021_t_err_Rsas_au230_ti3_fs_v777_l031_(所需信息在字符串末尾)

结论:我需要字符串的以下部分 l067 / l037 / l011 ..... 例如 l067 表示 67%,I037 表示 37%。所以我需要这两个百分比的值。结果是 6737。 我的代码:(仅部分)

for j=1:numRows;
Name=LaSP.Messung(j, 1).name
Size=size(Name)
Length = strlength(Name)%Evaluiert die Länge des gesamten Strings
pos1 = findstr(Name, '_')%Listet alle "_" im String auf
[zeile1,spalte1]=size(pos1)
spalte=pos1(1,spalte1)%ich hol mir string position vom letzten "_"

if spalte==Length%Abfrage ob das letzte zeichen ist ein "_"
%%Abfrage ob der Wert schon einmal vorkam   
    %%die letzten 4 auslesen
else 
    %%in mitten des strings
end

      %pos = strfind(Name, '_')
 %k = strfind(Name,'_','ForceCellOutput',true)
 %idx = find(strcmp(Name, '_'))
 %pat='_';
%ind=regexp(Name,pat);
% word_to_find=strfind(strarray,'stringtofind');
% starray.index(word_to_find);
end

我的问题是我无法拆分字符串...我无法提取最后 4 个字符... 谢谢

【问题讨论】:

  • 你可能想试试正则表达式
  • 感谢您发布所需的输入和输出以及代码,但代码有什么问题?你被困住了吗? (旁注:虽然不允许在 SO 上使用,但使用德语的代码内 cmets 会使非德语使用者更难理解)。我会在破折号上写一个strplit()_,然后抓住第九个单元格。

标签: string matlab find


【解决方案1】:

给定:

my_strings = {'011_c_srr_Rtzfi_at000_hh5_fs_v343_l067_i1_Test_Test',
'041_c_ddr_Rtzfi_ds000_hh5_fs_v343_l037_i1_Test_hall',
'061_t_err_Rsas_au000_ti3_fs_v777_l011_ *',
'021_t_err_Rsas_au230_ti3_fs_v777_l031_'};

这里很少有可能的解决方案。

  1. 使用regex 进行匹配,我们可以构建我们的模式来查找v 后跟三个数字和下划线的字符(例如v777_

    matches = regexp(my_strings,'v\d{3}_([^_]+)','tokens','once');
    [matches{:}]
    ans =
    
      1×4 cell array
    
      {'l067'}    {'l037'}    {'l011'}    {'l031'}
    
  2. 使用regex分割下划线,然后取第9个单元格:

    split_strings = regexp(my_strings,'_','split');
    matches = cellfun(@(x) x(9),split_strings).'
    ans =
    
     1×4 cell array
    
     {'l067'}    {'l037'}    {'l011'}    {'l031'}
    
  3. 使用strsplit分割下划线,然后取第9个单元格:

    n = numel(my_strings);
    matches = char.empty(0,n);
    for i = 1:n
      split_string = strsplit(my_strings{i},'_');
      matches = [matches split_string(9)];
    end
    matches =
    
      1×4 cell array
    
      {'l067'}    {'l037'}    {'l011'}    {'l031'}
    

【讨论】:

  • 你好,再问一个问题……如果不是第9格怎么办?
  • @FranzH 它是哪个单元格?只需9 到那个号码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
相关资源
最近更新 更多