Cover by Steven Levithan, Jan Goyvaerts

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required