How to further extract a match values from a regexp match

3 次查看(过去 30 天)
Hello,
Had a quick question regarding regexp.
Let's say you have some string and you want to extract certain values from it
string='hello_1_goodbye_0.23_hi_1.55_exit_1000'
regexp(string,'hello_\d+\.*\d*','match')
>>>
1x1 cell array
('hello_1')
From here I'd like to just extract the number. I'm not super familiar with matlab, but in python for example, in a regex search you can use parenthesis than extract the specific group of your match
pattern='hello_(\d+\.*\d*)'
regex_search.group(1)='1'
So the pattern is the same and you are still matching hello_1, but from there you are able to extract only the numerical value

采纳的回答

Vilém Frynta
Vilém Frynta 2023-6-1
If you use 'tokens' instead of match.
string = 'hello_2_goodbye_0.23_hi_1.55_exit_1000';
pattern = 'hello_(\d+\.*\d*)';
match = regexp(string, pattern, 'tokens');
num = match{1} % can be converted to number from a string
ans = 1×1 cell array
{'2'}
num = '2'
  2 个评论
Sam Mahdi
Sam Mahdi 2023-6-1
Ah thank you. I was getting an error because I was just trying to print out
regexp(string, pattern, 'tokens','match');
And kept getting errors regarding not enough outputs specified for tokens option. Thought maybe I was using it wrong, just had to remove the match option. Thank you!
Stephen23
Stephen23 2023-6-1
You might also want to use the ONCE option, to reduce the cell array nesting by one level:
S = 'hello_2_goodbye_0.23_hi_1.55_exit_1000';
P = 'hello_(\d+\.*\d*)';
C = regexp(S, P, 'tokens','once')
C = 1×1 cell array
{'2'}

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by