How to extract multiple numbers with regexp?

조회 수: 31 (최근 30일)
matuser123
matuser123 2016년 2월 16일
편집: Stephen23 2016년 2월 16일
I am trying to pull the ID from the following string.
'blah String XX blah'
where XX is the number that could be anything from 0 - 9999. I have tried the regular expression below but this only works for 0 - 9. Any ideas?
[aa,bb] = regexp(sss,'String (\d+)')
  댓글 수: 1
Stephen23
Stephen23 2016년 2월 16일
편집: Stephen23 2016년 2월 16일
What do you mean that it "only works for 0 - 9"? Your code correctly matches any number of digits:
>> [aa,bb] = regexp('blah String 9999 blah','String (\d+)')
aa =
6
bb =
16
Is this not what you expect?

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2016년 2월 16일
id = regexp(sss, '(?<=String\s+)(\d+)', 'match', 'once');
The result will be a cell array of string containing the matched string
If you want it more directly then
id = regexprep(sss, '(.*?String\s+)(\d+)(.*)', '$2', 'once');
The result would be a string directly.
The first version, the regexp version, is looking for digits proceeded by 'String' with the 'String' part marked up to indicate it is not to form part of the match.
The second version, the regexprep version, is matching on beginning of line to the first occurrence of 'String' as one group, matching on the digits as a second group, and matching to the end of the line as a third group, and is replacing the three matches with the content of the second group, thus effectively throwing away everything before and after the digits.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by