How to further extract a match values from a regexp match
조회 수: 4 (최근 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
댓글 수: 0
채택된 답변
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
댓글 수: 2
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')
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 String Parsing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!