Using Regexp to extract complete addresses

조회 수: 4 (최근 30일)
Jordan Barrett
Jordan Barrett 2021년 4월 6일
답변: Abhinav Aravindan 2025년 2월 24일
I'm trying to extract the addresses from a large pdf. Here is a screenshot of the pdf:
Here is the code I'm using:
str = extractFileText("document_name.pdf");
expression = '\d{1,8}\s\w*\s\w*\n';
startIndex = regexp(str,expression,'match');
However, this code only extracts addresses that begin with 1-8 digits, then have a space, then some letters, then a space, then more letters, then a new line.
As you can see in the screenshot, not all addresses are in this format. Some start with numbers, a space, then one word, then a new line, some have numbers then several words, then a new line, etc. How can I extract every full address?

답변 (1개)

Abhinav Aravindan
Abhinav Aravindan 2025년 2월 24일
From the screenshot provided, it seems that the addresses in your PDF start with a 4-digit number, followed by one or more words. Assuming each column in the screenshot is a page of the PDF, to extract addresses matching this pattern, you may iterate through each line of the PDF text and use the regular expression as mentioned in the code snippet below:
% PDF content
fileContent = extractFileText("document_name.pdf");
% Split the content into lines
lines = strsplit(fileContent, '\n');
addresses = [];
addressPattern = '\d{4}\s[A-Z\s]+';
% Extract addresses
for i = 1:length(lines)
line = strtrim(lines{i});
matches = regexp(line, addressPattern, 'match');
if ~isempty(matches)
addresses = [addresses; matches];
end
end
disp('Extracted Addresses:');
disp(addresses);
You may refer to the below documentation on “regexp” for more detail:

카테고리

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