Regular Expressions

Special Characters

The following characters have special functions in regular expressions, so they cannot be used literally (for example, if you had the string s@mple $earch, you could not replace the $ with an s by using regexr("s@mple $earch,"$","s").

[  \  ^  $  .  |  ?  *  +  (  )

Stata Date Formats

CharacterDescriptionExampleNotes
Any characterThat characterj matches j 
\ (backslash)
[\^%.|?*+()
Allows you to match special characters\% matches %
\\ matches \
accounts for  leap seconds
\n  \r  \tmatches a newline, carriage return, or a tab, respectively  

Character Classes

Character Classes are groupings of characters.  For example, if you wanted to find words starting with vowels, you would use [aeiou], or words containing the last 5 letters of the alphabet, you would use [w-z].  The special characters inside Character Classes are ^  -  ]  \.  Which means, you cane use $ or parantheses literally.

[any group of characters]will match any of the characters within the brackets[abc] matches a, b, or c 
\ (backslash)
^ - ] \
Allows you to include the special characters [\^\]] matches ^ or ] 
-denotes a range of characters[a-z] matches any letter between a and z
[1-5] matches 1, 2, 3, 4, or 5
 
^acts as negator: so it will match characters excluded from the Character Class [^aeiou] matches any consonant
.matches any single character sh.rt will match shirt or short or sh3rt, etc. 
^matches string at beginning expression ^cat matches cataract, cat, catemarang, etc. 
$matches string at end of expression tion$ matches motion, potion, solution, etc. 
|or operator ca|al matches cat, alligator, camera, etc. 
?makes preceding item optional cat? matches catapult, car, cake, etc. 
*repeats the previous item zero or more times M(iss)*i matches Mississippi, Missing, Milk, etc. 
+repeats the previous item one or more times M(iss)+i matches Mississippi, Missing, Missive, etc. (not Milk) 
{n}repeats the previous item n times   
{n,}repeats the previous item at least n times   
{n,m}repeats the previous item between n and m times