Regular Expressions: An Introduction

Published: January 12, 2004

Page » 1 2 3 4 5 6 7 8 9

Quantifiers

Quantifiers are those characters in the pattern, that specify how many characters to match. Or they "quantify" the the characters to match.

• * Quantifier: Match 0 or more characters (match any number of characters)
• ? Quantifier: Match 0 or 1 characters
• {min,max} Quantifier: Match (between min and max) characters
• {specific} Quantifier: Match (specific) number of characters

Taking a few examples

Wildcard a* Regex /a.*/ Explaintaion Match "a", then match anything Wildcard a? Regex /a.?/ Explaintaion Match "a", then match 0 or any character Wildcard *aaa* Regex /.*a{3}.*/ Explaintaion Match anything, followed by "aaa", followed by anything Wildcard a??? (Cann\'t completely define in Wildcards) Regex /a.{2,4}/ Explaintaion Match "a", then match 2, 3 or 4 character

Taking a few realtime matching cases of the last examples

Regex /a.{2,4}/ Explaintaion Match "a", then match 2, 3 or 4 character Example a False ab False abc True abcd True abcde True abcdef True

You can see in the last match, result is TRUE. This is becasue, we didn't specify where to match the pattern, so the pattern is matched in anywhere in the subject. And if you don't specify the location, it doesn't matter where the match is found.

However, if were to take the above example, with a slight change, and specify the location, interesting results come out. Lets see:

Regex /a.{2,4}\$/ Explaintaion At the end of the subject match "a", followed by 2, 3 or 4 characters Example a False ab False abc True abcd True abcde True abcdef False

As you can see, in the last match, result is False. To understand it, read the explaination carefully. At the end of the subject match "a", followed by 2, 3 or 4 characters. In simple terms we can say it again as "match a string which has third, fourth or fifth character from the end is a"

Page » 1 2 3 4 5 6 7 8 9