Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

README.md

DFURLRegularExpression

Synopsis

#import "DFURLRegularExpression.h"

NSTextCheckingResult *res = [[DFURLRegularExpression URLRegex]
    firstMatchInString:someText
    options:0
    range:(NSRange)NSMakeRange(0, someText.length)
];

if (res.range.location != NSNotFound) {
    NSLog(@"Found URL %@", [someText substringWithRange:res.range]);
}

A common programming problem: identify the URLs in an arbitrary string of text, where by “arbitrary” let’s agree we mean something unstructured such as an email message or a tweet. This class preents, as a solution, John Gruber's liberal URL-matching regular expression. It attempts to be practical, above all else. It makes no attempt to parse URLs according to any official specification. It isn’t limited to predefined URL protocols. It should be clever about things like parentheses and trailing punctuation.

It attempts to be particularly clever with regard to parentheses only ever seem to occur in the wild in Wikipedia URLs, and which many URL matching patterns seem to botch. The pattern looks for up to two levels of balanced, nested parentheses — parentheses within parentheses. Thus it correctly omits the trailing parenthesis in the following line:

(Something like http://foo.com/blah_blah)

The pattern is also liberal about Unicode glyphs within the URL, which allows it, among other things, to match IDN domain names, such as the ✪df.ws domain.

Usage

Just drag DFURLRegularExpression.h and DFURLRegularExpression.m into your project. Import them into whatever class you need them in and go! Here's the interface:

+URLRegex

Returns a regular expression for matching URLs.

+ (NSRegularExpression *)URLRegex

Return Value An NSRegularExpression object. Use its interface to search for URLs in text.

+webURLRegex

Returns a regular expression for matching only web URLs -- http, https, and things like “www.example.com”.

+ (NSRegularExpression *)webURLRegex

Return Value An NSRegularExpression object. Use its interface to search for web URLs in text.

Testing

This distribution ships with an Xcode project for running unit tests against the regular expressions. To run them, simply open the project in Xcode and build. Note that iOS 4.0 is required to use these regular expressions. Not sure if the tests can be run on Mac OS X.

Author

Copyright and License

(c) 2010 by John Gruber. This pattern is free for anyone to use, no strings attached. Consider it public domain.

Something went wrong with that request. Please try again.