Finding location of an exact match in a string

조회 수: 4 (최근 30일)
Thom Trentelman
Thom Trentelman 2018년 1월 4일
편집: Jan 2018년 1월 4일
I have imported a PDF file as string. I need to match '1.1.2' in the string to find its location. However '1.1.1.2' is also in it.
strfind(str,'1.1.2') returns ans = 71 134. It should only return 134.
How can I exactly match '1.1.2' without changing the PDF file string? Thank you!
----- edit:
I need to find the number using: number = [num2str(x),'.',num2str(y),'.',num2str(z)] since I need to trace multiple numbers in a loop.

채택된 답변

Guillaume
Guillaume 2018년 1월 4일
편집: Guillaume 2018년 1월 4일
Assuming that the '1.1.2' must be at the beginning of a line in a multiline string, this simple regular expression would work:
loc = regexp(yourstring, '^1\.1\.2[^.0-9]', 'lineanchors')
If the criteria is that '1.1.2' must not be preceded by a 'number dot' nor followed by a 'dot number' then:
loc = regexp(yourstring, '(?<!\d\.?)1\.1\.2[^.0-9]')
  댓글 수: 2
Thom Trentelman
Thom Trentelman 2018년 1월 4일
편집: Thom Trentelman 2018년 1월 4일
Got it!! Thank you!!
regexp(str,['^',num2str(x),'\.',num2str(y),'\.',num2str(z),'[^.]'],'lineanchors')
x = 1, y = 1, z = 2 ... :)))
Jan
Jan 2018년 1월 4일
편집: Jan 2018년 1월 4일
+1. "1.1.20" was not caught by the simple strfind methods.

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

추가 답변 (1개)

Jan
Jan 2018년 1월 4일
편집: Jan 2018년 1월 4일
List = strfind(str, '1.1.2');
Bad = strfind(str, '.1.1.2');
Match = setdiff(List, Bad + 1);
But this fails for "11.1.2". Which character occurs before the searched string?
List = strfind(str, '1.1.2');
Front = str(List - 1);
Valid = ~ismember(Front, '.1234567890');
Match = List(Valid)
This might work, but smart programmers would use a more powerful (and slower) regexp.
  댓글 수: 1
Guillaume
Guillaume 2018년 1월 4일
You state that you have a single string. Therefore, unless '1.1.2' is right at the beginning it is going to be preceded by some characters. You have told use that '1.' before it is not allowed but there may be other patterns that are not allowed. It is possible that the preceding character must always be a newline.
Knowing the exact details would help us.

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

카테고리

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