How can I extract the values from a file name?

Viewed 64

I have multiple files that has been named after the same way : 'RefBu12CyclesAmpl0.20Freq2.25VR0.0000Dist4cmSilence25000Fs25MHz' . I tried to make a function that returns the values and make the difference between strings and digits, but I can make it return the correct values.

Any ideas?

function [File] = get_somenthing(file_name)   
expression = '(?<Cycles>\d+)(?<Ampl>\D\S.+)(?<Freq>\d+)(?<VR>\d\S+)(?<Dist>\d.+)(?<Silence>\d+)(?<Fs>\d)'   
File = regexp(file_name,expression,'names')   
3 Answers

The following regular expresion matches digits optionally followed by a dot and digits. I assume the numbers are real, don't include signs, and cannot use scientific notation:

s = 'RefBu12CyclesAmpl0.20Freq2.25VR0.0000Dist4cmSilence25000Fs25MHz';
values_str = regexp(s, '\d+(\.\d+)?', 'match');
values = str2double(values_str);

This gives

>> values_str
values_str =
  1×7 cell array
    {'12'}    {'0.20'}    {'2.25'}    {'0.0000'}    {'4'}    {'25000'}    {'25'}

>> values
values =
   1.0e+04 *
   0.001200000000000   0.000020000000000   0.000225000000000                   0   0.000400000000000   2.500000000000000   0.002500000000000

This might work (it's not a function yet):

fn = 'RefBu12CyclesAmpl0.20Freq2.25VR0.0000Dist4cmSilence25000Fs25MHz';

pattern = 'RefBu(?<cycles>\d+)CyclesAmpl(?<ampl>\d+\.?\d*)Freq(?<freq>\d+\.?\d*)VR(?<vr>\d+\.?\d*)Dist(?<dist>\d+)cmSilence(?<silence>\d+)Fs(?<fs>\d+)MHz';

values = regexp(fn, pattern, 'names')

Result:

values = 

  struct with fields:

     cycles: '12'
       ampl: '0.20'
       freq: '2.25'
         vr: '0.0000'
       dist: '4'
    silence: '25000'
         fs: '25'

Maybe you can just split the string by characters, so everything left should be the numbers:

values = [ float(x) for x in re.split('[a-zA-Z]', fname) if x ]

or if you want to split filename in pairs of (name, value):

names_values = [ (x[0], float(x[1])) for x in re.findall(r'([a-zA-Z]+)(\d+[\.\d+]*)', fname) ]

Test: https://ideone.com/02JqmD

Related