3.3. Creating 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 ...
Get Regular Expressions Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.