MATLAB: Matlab: Select a variable name and find the corresponding value

MATLABregexp

Can somebody explain me how i get some specific values after the = sign? The input File is a .subvar file format. I dont know how to jump in the right row and column to get the value. Do you have a matlab tutorial link for such a problem.
I need for example two specific values (after the = sign): The value of $_Wk1_lr_m and $_Wk1_voll_m
Result: 15601 and 33690
!file.version=1.543!
! Test
subvargroup.begin ($G_Wk1)
subvar( $_Wk1_lr_C_x, str = ' 0.019 ' )
subvar( $_Wk1_lr_m, str = ' 15601 ' ) ! [kg] lr
subvar( $_Wk1_lr_C_y, str = '-0.007 ' )
subvar( $_Wk1_lr_C_z, str = ' 1.644 ' )
subvar( $_Wk1_voll_m, str = ' 33690 ' ) ! [kg] voll
subvargroup.end ($G_Wk1)

Best Answer

Here is one way:
content = fileread( 'myTextFile.txt' ) ;
match = regexp( content, '(?<=\$_Wk1_lr_m,\s+str\s*=\s*''\s*)[^\s'']+', 'match' ) ;
Wk1_lr_m = str2double( match ) ;
match = regexp( content, '(?<=\$_Wk1_voll_m,\s+str\s*=\s*''\s*)[^\s'']+', 'match' ) ;
Wk1_voll_m = str2double( match ) ;
Note that:
  • If there are multiple subgroups in your file, you will get vectors with all the values for these variables.
  • There are many possible approaches that we can adapt to your specific use-case if you provide more information.
We can imagine all sorts of patterns. This one does the following:
  • Match one or more characters that are neither a white-space nor a single quote: [^\s']+ (the ' must be doubled not to interfer with MATLAB char array delimiters)
  • Preceeded by (?<=..) (this is a look-backward) the literal \$_Wk1_voll_m, ($ must be escaped) followed by one or more white-space \s+, followed by the literal str, followed by one or more white-space, followed by the literal ' followed by zero or more white-spaces \s*.