> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/ios/get-started/samples/textsearchtest.md).

# TextSearch

Sample Obj-C code for using Apryse SDK to search text on PDF pages using regular expressions. The TextSearch utility class builds on functionality available in TextExtractor to simplify most common se

Sample Obj-C code for using Apryse SDK to search text on PDF pages using regular expressions. The TextSearch utility class builds on functionality available in [TextExtractor](/ios/get-started/samples.md#textextract) to simplify most common search operations. Learn more about our [iOS SDK](/ios/guides.md) and [PDF Indexed Search Library](/core/search/search.md).

{% tabs %}
{% tab title="Obj-C" %}
{% code lineNumbers="true" %}

```objc
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#import <OBJC/PDFNetOBJC.h>
#import <Foundation/Foundation.h>

// This sample illustrates the basic text search capabilities of PDFNet.

int main(int argc, char *argv[])
{
    @autoreleasepool {

        int ret = 0;
        [PTPDFNet Initialize: 0];
        NSString *input_path = @"../../TestFiles/credit card numbers.pdf";

        @try
        {
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithFilepath: input_path];
            [doc InitSecurityHandler];

            PTTextSearch *txt_search = [[PTTextSearch alloc] init];
            unsigned int mode = e_ptwhole_word | e_ptpage_stop;
            NSString *pattern = @"joHn sMiTh";

            //call Begin() method to initialize the text search.
            [txt_search Begin: doc pattern: pattern mode: mode start_page: -1 end_page: -1];

            int step = 0;
            
            //call Run() method iteratively to find all matching instances.
            while ( YES )
            {
                PTSearchResult *result = [txt_search Run];
                
                if ( result )
                {
                    if ( step == 0 )
                    {   //step 0: found "John Smith"
                        //note that, here, 'ambient_string' and 'hlts' are not written to, 
                        //as 'e_ambient_string' and 'e_highlight' are not set.

                        NSLog(@"%@'s credit card number is: ", [result GetMatch]);
                        //now switch to using regular expressions to find John's credit card number
                        mode = [txt_search GetMode];
                        mode |= e_ptreg_expression | e_pthighlight;
                        [txt_search SetMode: mode];
                        pattern = @"\\d{4}-\\d{4}-\\d{4}-\\d{4}"; //or "(\\d{4}-){3}\\d{4}"
                        [txt_search SetPattern: pattern];

                        ++step;
                    }
                    else if ( step == 1 )
                    {
                        //step 1: found John's credit card number
                        NSLog(@"  %@", [result GetMatch]);

                        //note that, here, 'hlts' is written to, as 'e_highlight' has been set.
                        //output the highlight info of the credit card number.
                        PTHighlights *hlts = [result GetHighlights];
                        [hlts Begin: doc];
                        while ( [hlts HasNext] )
                        {
                            NSLog(@"The current highlight is from page: %d", [hlts GetCurrentPageNumber]);
                            [hlts Next];
                        }

                        //see if there is an AMEX card number
                        pattern = @"\\d{4}-\\d{6}-\\d{5}";
                        [txt_search SetPattern: pattern];

                        ++step;
                    }
                    else if ( step == 2 )
                    {
                        //found an AMEX card number
                        NSLog(@"\nThere is an AMEX card number:\n  %@", [result GetMatch]);

                        //change mode to find the owner of the credit card; supposedly, the owner's
                        //name proceeds the number
                        mode = [txt_search GetMode];
                        mode |= e_ptsearch_up;
                        [txt_search SetMode: mode];
                        pattern = @"[A-z]++ [A-z]++";
                        [txt_search SetPattern: pattern];

                        ++step;
                    }
                    else if ( step == 3 )
                    {
                        //found the owner's name of the AMEX card
                        NSLog(@"Is the owner's name:\n  %@?\n", [result GetMatch]);

                        //add a link annotation based on the location of the found instance
                        PTHighlights *hlts = [result GetHighlights];
                        [hlts Begin: doc];
                        while ( [hlts HasNext] )
                        {
                            PTPage *cur_page = [doc GetPage: [hlts GetCurrentPageNumber]];
                            PTVectorQuadPoint *quads = [hlts GetCurrentQuads];
                            int i = 0;
                            for ( ; i < [quads size]; ++i )
                            {
                                //assume each quad is an axis-aligned rectangle
                                PTQuadPoint *q = [quads get: i];
                                double x1 = MIN(MIN(MIN([[q getP1] getX], [[q getP2] getX]), [[q getP3] getX]), [[q getP4] getX]);
                                double x2 = MAX(MAX(MAX([[q getP1] getX], [[q getP2] getX]), [[q getP3] getX]), [[q getP4] getX]);
                                double y1 = MIN(MIN(MIN([[q getP1] getY], [[q getP2] getY]), [[q getP3] getY]), [[q getP4] getY]);
                                double y2 = MAX(MAX(MAX([[q getP1] getY], [[q getP2] getY]), [[q getP3] getY]), [[q getP4] getY]);
                                PTPDFRect * rect = [[PTPDFRect alloc] initWithX1: x1 y1: y1 x2: x2 y2: y2];
                                PTAction *action = [PTAction CreateURI: [doc GetSDFDoc] uri: @"http://www.pdftron.com"];

                                PTLink *hyper_link = [PTLink CreateWithAction: [doc GetSDFDoc] pos: rect action: action];
                                [cur_page AnnotPushBack: hyper_link];
                            }
                            [hlts Next];
                        }
                        [doc SaveToFile: @"../../TestFiles/Output/credit card numbers_linked.pdf" flags: e_ptlinearized];

                        break;
                    }
                }

                else if ( [result IsPageEnd] )
                {
                    //you can update your UI here, if needed
                }

                else
                {
                    break;
                }
            }
        }

        @catch(NSException *e)
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }
        [PTPDFNet Terminate: 0];
        return ret;
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="Swift" %}
{% code lineNumbers="true" %}

```swift
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import PDFNet
import Foundation

// This sample illustrates the basic text search capabilities of PDFNet.

func runTextSearchTest() -> Int {
    return autoreleasepool {
        var ret: Int = 0
        
        let input_path: String? = Bundle.main.path(forResource: "credit card numbers", ofType: "pdf")
        
        do {
            try PTPDFNet.catchException {
                let doc: PTPDFDoc! = PTPDFDoc(filepath: input_path)
                doc.initSecurityHandler()
                
                let txt_search: PTTextSearch! = PTTextSearch()
                var mode = e_ptwhole_word.rawValue | e_ptpage_stop.rawValue
                var pattern = "joHn sMiTh"
                
                //call Begin() method to initialize the text search.
                txt_search.begin(doc, pattern: pattern, mode: mode, start_page: -1, end_page: -1)
                
                var step: Int = 0
                
                //call run() method iteratively to find all matching instances.
                while true {
                    let result: PTSearchResult! = txt_search.run()
                    
                    if (result != nil) {
                        if step == 0 {
                            //step 0: found "John Smith"
                            //note that, here, 'ambient_string' and 'hlts' are not written to,
                            //as 'e_ambient_string' and 'e_highlight' are not set.
                            
                            print("\(result.getMatch()!)'s credit card number is: ")
                            //now switch to using regular expressions to find John's credit card number
                            mode = txt_search.getMode()
                            mode |= e_ptreg_expression.rawValue | e_pthighlight.rawValue
                            txt_search.setMode(mode)
                            pattern = "\\d{4}-\\d{4}-\\d{4}-\\d{4}"
                            //or "(\\d{4}-){3}\\d{4}"
                            txt_search.setPattern(pattern)
                            
                            step += 1
                        } else if step == 1 {
                            //step 1: found John's credit card number
                            print("  \(result.getMatch()!)")
                            
                            //note that, here, 'hlts' is written to, as 'e_highlight' has been set.
                            //output the highlight info of the credit card number.
                            let hlts: PTHighlights = result.getHighlights()
                            hlts.begin(doc)
                            while hlts.hasNext() {
                                print("The current highlight is from page: \(hlts.getCurrentPageNumber())")
                                hlts.next()
                            }
                            
                            //see if there is an AMEX card number
                            pattern = "\\d{4}-\\d{6}-\\d{5}"
                            txt_search.setPattern(pattern)
                            
                            step += 1
                        } else if step == 2 {
                            //found an AMEX card number
                            print("There is an AMEX card number: \(result.getMatch()!)")
                            
                            //change mode to find the owner of the credit card; supposedly, the owner's
                            //name proceeds the number
                            mode = txt_search.getMode()
                            mode |= e_ptsearch_up.rawValue
                            txt_search.setMode(mode)
                            pattern = "[A-z]++ [A-z]++"
                            txt_search.setPattern(pattern)
                            step += 1
                        } else if step == 3 {
                            //found the owner's name of the AMEX card
                            print("Is the owner's name: \(result.getMatch()!)?")
                            
                            //add a link annotation based on the location of the found instance
                            let hlts: PTHighlights = result.getHighlights()
                            hlts.begin(doc)
                            while hlts.hasNext() {
                                let cur_page: PTPage = doc.getPage(UInt32(hlts.getCurrentPageNumber()))
                                let quads: PTVectorQuadPoint = hlts.getCurrentQuads()
                                var i: Int = 0
                                
                                while i < quads.size() {
                                    //assume each quad is an axis-aligned rectangle
                                    let q: PTQuadPoint = quads.get(Int32(i))
                                    let x1: Double = min(min(min(q.getP1().getX(), q.getP2().getX()), q.getP3().getX()), q.getP4().getX())
                                    let x2: Double = max(max(max(q.getP1().getX(), q.getP2().getX()), q.getP3().getX()), q.getP4().getX())
                                    let y1: Double = min(min(min(q.getP1().getY(), q.getP2().getY()), q.getP3().getY()), q.getP4().getY())
                                    let y2: Double = max(max(max(q.getP1().getY(), q.getP2().getY()), q.getP3().getY()), q.getP4().getY())
                                    let rect = PTPDFRect(x1: x1, y1: y1, x2: x2, y2: y2)
                                    let action = PTAction.createURI(doc.getSDFDoc(), uri: "http://www.pdftron.com")
                                    let hyper_link = PTLink.create(withAction: doc.getSDFDoc(), pos: rect, action: action)
                                    cur_page.annotPushBack(hyper_link)
                                    i += 1
                                }
                                hlts.next()
                            }
                            doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("credit card numbers_linked.pdf").path, flags: e_ptlinearized.rawValue)
                            
                            break
                        }
                    } else if (result.isPageEnd()) {
                        //you can update your UI here if needed
                    } else {
                        break
                    }
                }
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        return ret
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/ios/get-started/samples/textsearchtest.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
