Skip to Main Content
Regular Expressions Cookbook, 2nd Edition
book

Regular Expressions Cookbook, 2nd Edition

by Jan Goyvaerts, Steven Levithan
August 2012
Intermediate to advanced content levelIntermediate to advanced
609 pages
19h 16m
English
O'Reilly Media, Inc.
Content preview from Regular Expressions Cookbook, 2nd Edition

3.3. Create Regular Expression Objects

Problem

You want to instantiate a regular expression object or otherwise compile a regular expression so you can use it efficiently throughout your application.

Solution

C#

If you know the regex to be correct:

Regex regexObj = new Regex("regex pattern");

If the regex is provided by the end user (UserInput being a string variable):

try {
    Regex regexObj = new Regex(UserInput);
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

VB.NET

If you know the regex to be correct:

Dim RegexObj As New Regex("regex pattern")

If the regex is provided by the end user (UserInput being a string variable):

Try
    Dim RegexObj As New Regex(UserInput)
Catch ex As ArgumentException
    'Syntax error in the regular expression
End Try

Java

If you know the regex to be correct:

Pattern regex = Pattern.compile("regex pattern");

If the regex is provided by the end user (userInput being a string variable):

try {
	Pattern regex = Pattern.compile(userInput);
} catch (PatternSyntaxException ex) {
	// Syntax error in the regular expression
}

To be able to use the regex on a string, create a Matcher:

Matcher regexMatcher = regex.matcher(subjectString);

To use the regex on another string, you can create a new Matcher, as just shown, or reuse an existing one:

regexMatcher.reset(anotherSubjectString);

JavaScript

Literal regular expression in your code:

var myregexp = /regex pattern/;

Regular expression retrieved from user input, as a string stored in the variable userinput:

var myregexp ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Regular Expressions, 3rd Edition

Mastering Regular Expressions, 3rd Edition

Jeffrey E.F. Friedl
Regular Expressions Cookbook

Regular Expressions Cookbook

Jan Goyvaerts, Steven Levithan

Publisher Resources

ISBN: 9781449327453Supplemental ContentErrata Page