Lua Requires Chilkat v11.7.0+
Lua
Search a PDF with a Regular Expression
See more PDF Text Extraction Examples
Demonstrates searching a PDF with a regular expression (regex: true), limiting the number of results (maxResults), and matching whole words only (wholeWord).Chilkat Lua Downloads
local chilkat = require("chilkat")
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
-- The PDF used in this example is available at order_records.pdf
local pdf = chilkat.Pdf.new()
local success = pdf:load_file("qa_data/pdf/order_records.pdf")
if not success then
print(pdf.last_error_text)
return
end
local json = chilkat.JsonObject.new()
local jsonOut = chilkat.JsonObject.new()
-- Find every order number. With regex set to true, the query is a regular expression.
json:update_string("query", "ORD-[0-9]{4}-[0-9]{4}")
json:update_bool("regex", true)
-- We only want the matched text, so no context is needed.
json:update_int("context", 0)
success = pdf:extract_text("search", json, jsonOut)
if not success then
print(pdf.last_error_text)
return
end
print("Order numbers found: " .. jsonOut:int_of("count"))
local i = 0
local count_i = jsonOut:size_of_array("matches")
while i < count_i do
jsonOut.i = i
print(jsonOut:string_of("matches[i].text"))
i = i + 1
end
-- Find the e-mail addresses, but stop after the first three.
json:update_string("query", "[a-z0-9._]+@[a-z]+[.][a-z]+")
json:update_int("maxResults", 3)
success = pdf:extract_text("search", json, jsonOut)
if not success then
print(pdf.last_error_text)
return
end
print("First three e-mail addresses:")
i = 0
count_i = jsonOut:size_of_array("matches")
while i < count_i do
jsonOut.i = i
print(jsonOut:string_of("matches[i].text"))
i = i + 1
end
-- wholeWord: true matches only whole words. The word "cat" appears once in the PDF,
-- but it is also inside "catalog" and "category".
json:delete("maxResults")
json:update_bool("regex", false)
json:update_string("query", "cat")
success = pdf:extract_text("search", json, jsonOut)
if not success then
print(pdf.last_error_text)
return
end
print("Occurrences of cat (any): " .. jsonOut:int_of("count"))
json:update_bool("wholeWord", true)
success = pdf:extract_text("search", json, jsonOut)
if not success then
print(pdf.last_error_text)
return
end
print("Occurrences of cat (whole word): " .. jsonOut:int_of("count"))
-- Sample output:
-- Order numbers found: 9
-- ORD-2026-0301
-- ORD-2026-0302
-- ORD-2026-0303
-- ORD-2026-0304
-- ORD-2026-0305
-- ORD-2026-0306
-- ORD-2026-0307
-- ORD-2026-0308
-- ORD-2026-0307
-- First three e-mail addresses:
-- alice.moore@example.com
-- bkumar@example.org
-- carla@example.net
-- Occurrences of cat (any): 3
-- Occurrences of cat (whole word): 1