Regular Expressions Introduction For information on what regular expressions are (or how to create them), consult the wiki. RegEx Patterns Here is a quick reference for patterns: Code: +-------------+--------------------------------------------------------------+ | Expression | Description | +-------------+--------------------------------------------------------------+ | . | Any character except newline. | +-------------+--------------------------------------------------------------+ | \. | A period (and so on for \*, \(, \\, etc.) | +-------------+--------------------------------------------------------------+ | ^ | The start of the string. | +-------------+--------------------------------------------------------------+ | $ | The end of the string. | +-------------+--------------------------------------------------------------+ | \d,\w,\s | A digit, word character [A-Za-z0-9_], or whitespace. | +-------------+--------------------------------------------------------------+ | \D,\W,\S | Anything except a digit, word character, or whitespace. | +-------------+--------------------------------------------------------------+ | [abc] | Character a, b, or c. | +-------------+--------------------------------------------------------------+ | [a-z] | a through z. | +-------------+--------------------------------------------------------------+ | [^abc] | Any character except a, b, or c. | +-------------+--------------------------------------------------------------+ | aa|bb | Either aa or bb. | +-------------+--------------------------------------------------------------+ | ? | Zero or one of the preceding element. | +-------------+--------------------------------------------------------------+ | * | Zero or more of the preceding element. | +-------------+--------------------------------------------------------------+ | + | One or more of the preceding element. | +-------------+--------------------------------------------------------------+ | {n} | Exactly n of the preceding element. | +-------------+--------------------------------------------------------------+ | {n,} | n or more of the preceding element. | +-------------+--------------------------------------------------------------+ | {m,n} | Between m and n of the preceding element. | +-------------+--------------------------------------------------------------+ | ??,*?,+?, | Same as above, but as few as possible. | | {n}?, etc. | | +-------------+--------------------------------------------------------------+ | (expr) | Capture expr for use with \1, etc. | +-------------+--------------------------------------------------------------+ | (?:expr) | Non-capturing group. | +-------------+--------------------------------------------------------------+ | (?=expr) | Followed by expr. | +-------------+--------------------------------------------------------------+ | (?!expr) | Not followed by expr. | +-------------+--------------------------------------------------------------+ Example: Let's try to catch a swear work, like "ass". We could simply make our pattern "ass" and it would match it. But, it would also match "glass" or "brass", so how do we fix that? We add a non-character requirement in front of ass. So we would do this: "\Wass", which means allow anything except for a letter before "ass". Now, "glass" or "brass" won't get picked, but now just "ass" won't because it requires something besides a letter in front. To fix this, we make the non-character requirement also allow nothing in front, like so: "\W*ass" We're still not done yet. What about the word "assassin"? That will still get picked up because it matches the first "ass" in "assassin". So now we have to allow nothing, or anything except a character, after it: "\W*ass\W*" Looks good, right? Now, we need to add checking for people who would type variations, like asssss or aaasssss. So, let's just say any number of A's and at least 2 S's: "\W*a+s{2,}\W*" One last thing is checking for non-alphabetic characters to look like those letters, like a$$. Well, let's see what looks alike: a = @, 4, /\, /-\ s = 5, z, $ Now, let's transform them into character classes: a = (?:[a@4]|\/\\|\/-\\) s = [s5z\$] We had to put A's in a non-capturing group since /\ and /-\ are more than 1 character and won't work for character classes. I used a non-capturing group so every A isn't put into the matches when checked. Also, the slashes in A's and the dollar sign in S's needed to be escaped. Add those to the pattern now: "\W*(?:[a@4]|\/\\|\/-\\)+[s5z\$]{2,}\W*" Finally, let's add the ignore case-sensitivity flag to allow capital letters checking: /\W*(?:[a@4]|\/\\|\/-\\)+[s5z\$]{2,}\W*/i That's how you create RegEx patterns, and they normally do look crazy when you're done with them so be sure to comment what they are for in case you need to go back to them later. RegEx Flags Flags were introduced to AMXX in version 1.8. These are the flags you can use with your patterns: i - Ignore case - Ignores case sensitivity with your pattern, so /a/i would be "a" and "A" m - Multilines - Affects ^ and $ so that they match the start/end of a line rather than the start/end of the string s - Single line - Affects . so it matches any character, even new line characters x - Pattern extension - Ignore whitespace and # comments RegEx in AMXX In most languages, you will see this format for the expression: /pattern/flags In AMXX, the pattern and flags are separated, and those slashes are taken away. So if you had this pattern: /[ch]+at/i It would be split into: - pattern: [ch]+at - flags: i Do not escape for new line characters (or other escapable characters) with Pawns escape character, like ^n. Instead, use the RegEx escape with \n. Using RegEx First, you'll need to include regex.inc: Code: #include These are the error codes from matching: Code: enum Regex { REGEX_MATCH_FAIL = -2, REGEX_PATTERN_FAIL, REGEX_NO_MATCH, REGEX_OK }; Checking if a string matches a pattern is simple. Spoiler Code: /** * Matches a string against a regular expression pattern. * * @note If you intend on using the same regular expression pattern * multiple times, consider using regex_compile and regex_match_c * instead of making this function reparse the expression each time. * * @param string The string to check. * @param pattern The regular expression pattern. * @param ret Error code, or result state of the match. * @param error Error message, if applicable. * @param maxLen Maximum length of the error buffer. * @param flags General flags for the regular expression. * i = Ignore case * m = Multilines (affects ^ and $ so that they match * the start/end of a line rather than matching the * start/end of the string). * s = Single line (affects . so that it matches any character, * even new line characters). * x = Pattern extension (ignore whitespace and # comments). * * @return -2 = Matching error (error code is stored in ret) * -1 = Error in pattern (error message and offset # in error and ret) * 0 = No match. * >1 = Handle for getting more information (via regex_substr) * * @note Flags only exist in amxmodx 1.8 and later. * @note You should free the returned handle (with regex_free()) * when you are done extracting all of the substrings. */ native Regex:regex_match(const string[], const pattern[], &ret, error[], maxLen, const flags[] = ""); Example: Spoiler Code: new const string[] = "123.456" new ret, error[128] new Regex:regex_handle = regex_match(string, "\d+\.\d+", ret, error, charsmax(error)) switch(regex_handle) { case REGEX_MATCH_FAIL: { // There was an error matching against the pattern // Check the {error} variable for message, and {ret} for error code } case REGEX_PATTERN_FAIL: { // There is an error in your pattern // Check the {error} variable for message, and {ret} for error code } case REGEX_NO_MATCH: { // Matched string 0 times } default: { // Matched string {ret} times // Free the Regex handle regex_free(regex_handle); } } You can get the individual matches (if you supplied groupings). Spoiler Code: /** * Returns a matched substring from a regex handle. * Substring ids start at 0 and end at ret-1, where ret is from the corresponding * regex_match or regex_match_c function call. * * @param id The regex handle to extract data from. * @param str_id The index of the expression to get - starts at 0, and ends at ret - 1. * @param buffer The buffer to set to the matching substring. * @param maxLen The maximum string length of the buffer. * */ native regex_substr(Regex:id, str_id, buffer[], maxLen); Example, grabbing the numbers from a SteamID: Spoiler Code: new const steamID[] = "STEAM_0:1:23456" new ret, error[128] new Regex:regex_handle = regex_match(steamID, "^^STEAM_0:[01]:(\d+)$", ret, error, charsmax(error)) if(regex_handle > REGEX_NO_MATCH) { // 0 string ID is always the whole string that matched // After 0 are the groupings new numbers[32] regex_substr(regex_handle, 1, numbers, charsmax(numbers)) // numbers = "23456" regex_free(regex_handle) } Compiling Patterns When you have a pattern that will be used more than one time, it is more efficient to compile it. Spoiler Code: /** * Precompile a regular expression. Use this if you intend on using the * same expression multiple times. Pass the regex handle returned here to * regex_match_c to check for matches. * * @param pattern The regular expression pattern. * @param errcode Error code encountered, if applicable. * @param error Error message encountered, if applicable. * @param maxLen Maximum string length of the error buffer. * @param flags General flags for the regular expression. * i = Ignore case * m = Multilines (affects ^ and $ so that they match * the start/end of a line rather than matching the * start/end of the string). * s = Single line (affects . so that it matches any character, * even new line characters). * x = Pattern extension (ignore whitespace and # comments). * * @return -1 on error in the pattern, > valid regex handle (> 0) on success. * * @note This handle is automatically freed on map change. However, * if you are completely done with it before then, you should * call regex_free on this handle. */ native Regex:regex_compile(const pattern[], &ret, error[], maxLen, const flags[]=""); Example: Spoiler Code: new ret, error[128] new Regex:regex_handle = regex_compile("^^STEAM_0:[01]:(\d+)$", ret, error, charsmax(error)) if(regex_handle != REGEX_PATTERN_FAIL) { // Match against strings } When matching against strings, you have to use another match function: Spoiler Code: /** * Matches a string against a pre-compiled regular expression pattern. * * * @param pattern The regular expression pattern. * @param string The string to check. * @param ret Error code, if applicable, or number of results on success. * * @return -2 = Matching error (error code is stored in ret) * 0 = No match. * >1 = Number of results. * * @note You should free the returned handle (with regex_free()) * when you are done with this pattern. * * @note Use the regex handle passed to this function to extract * matches with regex_substr(). */ native regex_match_c(const string[], Regex:pattern, &ret); Example: Spoiler Code: new ret, error[128] new Regex:regex_handle = regex_compile("^^STEAM_0:[01]:(\d+)$", ret, error, charsmax(error)) if(regex_handle != REGEX_PATTERN_FAIL) { new players[32], pnum get_players(players, pnum, "ch") new steamID[35], number[32] for(new i = 0; i < pnum; i++) { get_user_authid(players[i], steamID, charsmax(steamID)) if(regex_match_c(steamID, regex_handle, ret) > 0) { regex_substr(regex_handle, 1, numbers, charsmax(numbers)) // numbers = trailing numbers in SteamID of this player } } regex_free(regex_handle) } Another example for compiling: Spoiler Code: #include #include new Regex:gPatternSteamID = REGEX_PATTERN_FAIL // Default to invalid handle public plugin_init() { new ret, error[128] gPatternSteamID = regex_compile("^^STEAM_0:[01]:\d+$", ret, error, charsmax(error)) if(gPatternSteamID == REGEX_PATTERN_FAIL) { log_amx("Error creating SteamID pattern (%d): %s", ret, error) } } stock bool:IsValidSteamID(const string[]) { new ret return (gPatternSteamID != REGEX_PATTERN_FAIL && regex_match_c(string, gPatternSteamID, ret) > 0) } RegEx Tester RegEx Tester is a plugin I wrote to be able to check strings against a pattern via the server console. Command: - regex_pattern - regex_test The pattern can be in /pattern/flags format or just the pattern itself. Example: Code: ] regex_pattern "^STEAM_0:[01]:\d+$" Pattern set to: ^STEAM_0:[01]:\d+$ Flags set to: ] regex_test "STEAM_0:1:23456" 1 matches 1. "STEAM_0:1:23456" ] regex_pattern "/^STEAM_0:[01]:\d+$/i" Pattern set to: ^STEAM_0:[01]:\d+$ Flags set to: i ] regex_test "steam_0:1:23456" 1 matches 1. "steam_0:1:23456" You can use this if you are unsure whether or not your pattern will work.