Does MATLAB require a 2nd REGEXP to match data values obtained from a previous REGEXP?

조회 수: 4 (최근 30일)
I've got a set of commands that look like this:
str = 'Part ID: 1 or Part ID: 2 or Part ID: 5 or Part ID: 10';
exp = '*?Part ID:\s+(\d+)';
tokens = regexp(str, exp, 'tokens');
Part_data = reshape(str2double([tokens{:}]), 1, []).'
The objective of the code is to match only Part ID values 2 and 5. MATLAB is easily extracting all 4 part IDs with the commands above. However, I can't get MATLAB to read ONLY values 2 and 5.
I've been seearching Mathworks and using the MATLAB documentation in hopes of answering the following question: Does MATLAB require a 2nd REGEXP to match data values obtained from a previous REGEXP? Or am I making this harder than it is?
  댓글 수: 2
Ken Atwell
Ken Atwell 2013년 5월 24일
What is it that makes values 2 and 5 different/special ("keepers") from 1 and 10 ("non-keepers")?
Brad
Brad 2013년 5월 24일
Ken, These values are tied to other parameters that require additional processing.

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

채택된 답변

Walter Roberson
Walter Roberson 2013년 5월 24일
exp = 'Part ID:\s+([25])\W';
The expression will match as many times as needed

추가 답변 (1개)

James Kristoff
James Kristoff 2013년 5월 24일
The quick solution to the objected you stated is to use a more specific regular expression, i.e. if you only want the values 2 and 5:
exp = '*?Part ID:\s+([2|5])';
The real question is:
  • what is the actual motivation behind your question?
Meaning, if you just always want to get 2 and 5, then why not have a static vector of 2 and 5.
  • What makes 2 and 5 special/different from 1 and 10?
It is that difference or uniqueness that you should use to isolate the values you want in a more generic algorithm.
  댓글 수: 2
Walter Roberson
Walter Roberson 2013년 5월 24일
[2|5] means "2" or "|" or "5", not "2" or "5". [25] already means "2" or "5"
James Kristoff
James Kristoff 2013년 5월 24일
Also, a cleaner way of creating a vector of doubles from a cell array is to use the cellfun command, e.g.
Part_data = cellfun(@(str)str2double(str), tokens)

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

카테고리

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