You want to check whether a string fits a certain pattern in its
entirety. That is, you want to check that the regular expression holding
the pattern can match the string from start to end. For instance, if
your regex is ‹regex●pattern
›, it will match
input text consisting of regex pattern
but not the longer string
The regex pattern can be
found
.
For quick one-off tests, you can use the static call:
bool foundMatch = Regex.IsMatch(subjectString, @"Aregex pattern
");
To use the same regex repeatedly, construct a Regex
object:
Regex regexObj = new Regex(@"Aregex pattern
");
bool foundMatch = regexObj.IsMatch(subjectString);
For quick one-off tests, you can use the static call:
Dim FoundMatch = Regex.IsMatch(SubjectString, "Aregex pattern
")
To use the same regex repeatedly, construct a Regex
object:
Dim RegexObj As New Regex("Aregex pattern
")
Dim FoundMatch = RegexObj.IsMatch(SubjectString)
The IsMatch()
call should
have SubjectString
as the only
parameter, and the call should be made on the RegexObj
instance rather than the Regex
class:
Dim FoundMatch = RegexObj.IsMatch(SubjectString)
If you want to test just one string, you can use the static call:
boolean foundMatch = subjectString.matches("regex pattern
");
If you want to use the same regex on multiple strings, compile your regex and create a matcher:
Pattern regex = Pattern.compile("regex pattern
");
Matcher regexMatcher = regex.matcher(subjectString);
boolean foundMatch = regexMatcher.matches(subjectString);
if (preg_match('/Aregex pattern
/', $subject)) {
# Successful match
} else {
# Match attempt failed
}
For quick one-off tests, you can use the global function:
if re.match(r"regex pattern
", subject):
# Successful match
else:
# Match attempt failed
To use the same regex repeatedly, use a compiled object:
reobj = re.compile(r"regex pattern
")
if reobj.match(subject):
# Successful match
else:
# Match attempt failed
Normally, a successful regular expression match tells you that the pattern you want is somewhere within the subject text. In many situations you also want to make sure it completely matches, with nothing else in the subject text. Probably the most common situation calling for a complete match is validating input. If a user enters a phone number or IP address but includes extraneous characters, you want to reject the input.
The solutions that use the anchors ‹$
› and ‹› also
work when you’re processing a file line by line (Recipe 3.21), and the mechanism you’re using to
retrieve the lines leaves the line breaks at the end of the line. As
Recipe 2.5 explains, these anchors also match
before a final line break, essentially allowing the final line break to
be ignored.
In the following subsections, we explain the solutions for various languages in detail.
The Regex
class in the .NET Framework does not have a function for testing
whether a regex matches a string entirely. The solution is to add the
start-of-string anchor ‹A
› to
the start of your regular expression, and the end-of-string anchor
‹› to the end of your
regular expression. This way, the regular expression can only match a
string either in its entirety or not at all. If your regular
expression uses alternation, as in ‹
one|two|three
›, make sure to group the
alternation before adding the anchors: ‹A(?:one|two|three)
›.
With your regular expression amended to match whole strings, you
can use the same IsMatch()
method as described in the previous
recipe.
Java has three methods called matches()
. They all check whether a regex can
match a string entirely. These methods are a quick way to do input
validation, without having to enclose your regex with start-of-string
and end-of-string anchors.
The String
class has a matches()
method that takes a regular expression as the only parameter. It
returns true
or
false
to indicate
whether the regex can match the whole string. The Pattern
class has a static matches()
method, which takes two strings: the first is the regular expression,
and the second is the subject string. Actually, you can pass any
CharSequence
as the subject string to Pattern.matches()
. That’s the only reason for
using Pattern.matches()
instead of String.matches()
.
Both String.matches()
and
Pattern.matches()
recompile the regular expression each time by calling Pattern.compile("regex").matcher(subjectString).matches()
.
Because the regex is recompiled each time, you should use these calls
only when you want to use the regex only once (e.g., to validate one
field on an input form) or when efficiency is not an issue. These
methods don’t provide a way to specify matching options outside of the
regular expression. A PatternSyntaxException
is thrown if your regular
expression has a syntax error.
If you want to use the same regex to test many strings
efficiently, you should compile your regex and create and reuse a
Matcher
, as explained
in Recipe 3.3. Then call matches()
on your Matcher
instance. This function does not take any parameters, because you’ve
already specified the subject string when creating or resetting the
matcher.
JavaScript does not have a function for testing whether
a regex matches a string entirely. The solution is to add ‹^
› to the start of your regular
expression, and ‹$
› to
the end of your regular expression. Make sure that you do not set the
/m
flag
for your regular expression. Only without /m
do the
caret and dollar match only at the start and end of the subject
string. When you set /m
, they
also match at line breaks in the middle of the string.
With the anchors added to your regular expression, you can use
the same regexp.test()
method described in the previous recipe.
PHP does not have a function for testing whether a regex
matches a string entirely. The solution is to add the start-of-string
anchor ‹A
› to the start
of your regular expression, and the end-of-string anchor ‹› to the end of your regular
expression. This way, the regular expression can only match a string
either in its entirety or not at all. If your regular expression uses
alternation, as in ‹
one|two|three
›, make sure to group the
alternation before adding the anchors: ‹A(?:one|two|three)
›.
With your regular expression amended to match whole strings, you
can use the same preg_match()
function as described in the
previous recipe.
Perl has only one pattern-matching operator, which is
satisfied with partial matches. If you want to check whether your
regex matches the whole subject string, add the start-of-string anchor ‹A
› to the start of your regular
expression, and the end-of-string anchor ‹› to the end of your regular expression. This
way, the regular expression can only match a string either in its
entirety or not at all. If your regular expression uses alternation,
as in ‹
one|two|three
›,
make sure to group the alternation before adding the anchors: ‹A(?:one|two|three)
›.
With your regular expression amended to match whole strings, use it as described in the previous recipe.
The match()
function is very similar to the search()
function described in the previous
recipe. The key difference is that match()
evaluates the regular expression only at the very beginning of the
subject string. If the regex does not match at the start of the
string, match()
returns None
right
away. The search()
function, however, will keep trying the regex at each successive
position in the string until it either finds a match or reaches the
end of the subject string.
The match()
function does not require the regular expression to match the whole
string. A partial match is accepted, as long as it begins at the start
of the string. If you want to check whether your regex can match the
whole string, append the end-of-string anchor ‹› to your regular expression.
Ruby’s Regexp
class does not have a function for testing whether a regex matches a
string entirely. The solution is to add the start-of-string anchor
‹A
› to the start of
your regular expression, and the end-of-string anchor ‹› to the end of your regular
expression. This way, the
regular expression can only match a string either in its entirety or
not at all. If your regular expression uses alternation, as in
‹
one|two|three
›, make
sure to group the alternation before adding the anchors: ‹A(?:one|two|three)
›.
With your regular expression amended to match whole strings, you
can use the same =~
operator as described in the previous recipe.
Recipe 2.5 explains in detail how anchors work.
Recipes 2.8 and 2.9 explain alternation and grouping. If your regex uses alternation outside of any groups, you need to group your regex before adding the anchors. If your regex does not use alternation, or if it uses alternation only within groups, then no extra grouping is needed to make the anchors work as intended.
Follow Recipe 3.5 when partial matches are acceptable.