How-To: Common Regex Patterns for Log Extraction

This article provides ready-to-use regular expression patterns for extracting common fields from log files. You can copy these patterns and use them in your queries with the regex() function.

Hostnames and FQDNs

Extract hostnames and fully qualified domain names from log entries.

Simple hostname:

logscale
regex(regex="host[=:]?\s*(?<hostname>[\w-]+)")

Fully qualified domain name (FQDN):

logscale
regex(regex="host[=:]?\s*(?<fqdn>[\w-]+\.[\w.-]+)")

IP Addresses

Extract IPv4 and IPv6 addresses from log files.

IPv4 address:

logscale
regex(regex="(?<ipv4>\b(?:\d{1,3}\.){3}\d{1,3}\b)")

IPv6 address:

logscale
regex(regex="(?<ipv6>(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4})")

File Paths

Extract file paths and file names from logs.

Linux/Unix path:

logscale
regex(regex="(?<filepath>/[\w/.-]+)")

Windows path:

logscale
regex(regex="(?<filepath>[A-Za-z]:\\\\[\w\\\\.-]+)")

Windows path (excluding spaces and quotes):

logscale
regex(regex="(?<proc_path>[A-Za-z]:\\\\[^\\s\"]+)")

This enhanced Windows path pattern uses [^\\s\"]+ to match any character except spaces and quotes. This prevents over-matching in logs where paths might be followed by arguments or other quoted strings. More robust for production environments where paths appear in command lines or structured text.

File extension:

logscale
regex(regex="\.(?<extension>log|txt|exe|dll|conf|xml|json)\b")

File name from path:

logscale
regex(regex="[\\/](?<filename>[\w.-]+\.\w+)$")

Process and Executable Names

Extract process names and executable names from logs.

Windows executable:

logscale
regex(regex="(?<process>\w+\.exe)\b")

Unix process name:

logscale
regex(regex="process[=:]?\s*(?<process>[\w.-]+)")

Match reconnaissance tools (using alternation and anchors):

logscale
FileName = /^(net|ipconfig|whoami|quser|ping|netstat|tasklist|hostname)\.exe$/i

This pattern matches common reconnaissance tool executables used in security investigations. The components:

  • ^ anchors to the start โ€” ensures the match begins at the start of the field

  • $ anchors to the end โ€” ensures the match ends at the end of the field

  • | provides alternation (OR) โ€” matches any one of the listed reconnaissance tools

  • i flag makes the match case-insensitive โ€” matches both cmd.exe and CMD.EXE

The anchors prevent partial matches. For example, the pattern matches net.exe but does not match dotnet.exe because ^ requires the match to start at the beginning of the field.

Windows Event ID:

logscale
regex(regex="EventID=(?<event_id>\d+)")

Extracts Windows Event IDs from Windows Event Logs. Common in security monitoring and system administration for tracking specific event types like logon events (4624), account creation (4720), or security audit failures (4625).

Usernames

Extract usernames in different formats from authentication logs.

Email format (user@domain):

logscale
regex(regex="(?<username>[\w.-]+@[\w.-]+)")

Domain format (DOMAIN\user):

logscale
regex(regex="(?<domain>[\w-]+)\\\\(?<username>[\w.-]+)")

Simple username:

logscale
regex(regex="user[=:]?\s*(?<username>[\w.-]+)")

Email with separate username and domain capture:

logscale
regex(field=email, regex="(?<username>[^@]+)@(?<domain>.+)")

This pattern splits an email address into two separate fields: username (everything before the @) and domain (everything after). The [^@]+ matches any character except @, ensuring it stops at the @ symbol.

Log Levels

Extract log severity levels from application logs.

logscale
regex(regex="(?<log_level>ERROR|WARN|WARNING|INFO|DEBUG|TRACE|FATAL)\b")

Timestamps

Extract timestamps in common log formats.

ISO8601 format (2024-01-15T10:30:45):

logscale
regex(regex="(?<timestamp>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})")

Syslog format (Jan 15 10:30:45):

logscale
regex(regex="(?<timestamp>(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}\s+\d{2}:\d{2}:\d{2})")

Apache/NCSA format (15/Jan/2024:10:30:45):

logscale
regex(regex="(?<timestamp>\d{2}/\w{3}/\d{4}:\d{2}:\d{2}:\d{2})")

Date only - YYYY-MM-DD format (ISO date):

logscale
regex(regex="(?<date>\d{4}-\d{2}-\d{2})")

Date only - MM/DD/YYYY format (US date):

logscale
regex(regex="(?<date>\d{2}/\d{2}/\d{4})")

Date only - DD-MM-YYYY format (European date):

logscale
regex(regex="(?<date>\d{2}-\d{2}-\d{4})")

Hour (24-hour format, 00-23):

logscale
regex(regex="(?<hour>[01]\d|2[0-3]):")

This pattern matches hours from 00 to 23. [01]\d matches 00-19, and 2[0-3] matches 20-23.

Minutes (00-59):

logscale
regex(regex=":(?<minutes>[0-5]\d):")

Seconds (00-59):

logscale
regex(regex=":(?<seconds>[0-5]\d)\b")

Milliseconds (3 digits):

logscale
regex(regex="\.(?<milliseconds>\d{3})")

Complete time (HH:MM:SS.mmm):

logscale
regex(regex="(?<time>(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d\.\d{3})")

URLs and URIs

Extract URLs, domains, and API endpoints from web logs.

Full URL:

logscale
regex(regex="(?<url>https?://[\w.-]+(?:/[\w/.-]*)?)")

Domain name:

logscale
regex(regex="(?<domain>(?:[\w-]+\.)+[a-zA-Z]{2,})")

URI path:

logscale
regex(regex="(?:GET|POST|PUT|DELETE|PATCH)\s+(?<uri>/[\w/.-]*)")

Domain from URL with protocol (from referer logs):

logscale
regex(regex="https?:\\/\\/(?<domain>.+?)(\\/|\\?|$)", field=referer)

This pattern extracts the domain from a full URL by matching everything after http:// or https:// until the first slash, question mark, or end of string. The .+? uses non-greedy matching to stop at the first delimiter. This pattern is used in the Apache HTTP Server package for referer analysis.

Domain from URL field (without protocol):

logscale
regex(regex="^(?<domain>.*?)(\\/|$)", field=url.original, strict=false)

Extracts the domain portion when the URL field does not include the protocol. Matches from the start (^) until the first slash or end of string. This pattern is used in the Zscaler package for web activity analysis.

File extension from URL path:

logscale
regex(regex="\\.(?<media_type>[A-Za-z]+)", field=url)

Extracts the file extension after the last dot in a URL path. Useful for categorizing requests by media type (html, json, pdf, and so on). This pattern is used in the Apache HTTP Server package for media type analysis.

URL path components (category and ID):

logscale
regex(regex="/products/(?<category>.+)/(?<productId>.+) HTTP/")

Extracts multiple components from a URL path in one pattern. This example captures both the category and product ID from paths like /products/electronics/12345 HTTP/1.1. Useful for analyzing API endpoint usage.

HTTP Status Codes and Methods

Extract HTTP-related information from web server logs.

HTTP status code:

logscale
regex(regex="status[=:]?\s*(?<status_code>[1-5]\d{2})")

HTTP method:

logscale
regex(regex="(?<http_method>GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\b")

Port Numbers

Extract port numbers from network logs.

logscale
regex(regex="port[=:]?\s*(?<port>\d{1,5})")

Port from IP:port format:

logscale
regex(regex="(?:\d{1,3}\.){3}\d{1,3}:(?<port>\d{1,5})")

UUIDs, GUIDs, and Hashes

Extract universally unique identifiers and cryptographic hashes from logs.

UUID/GUID:

logscale
regex(regex="(?<uuid>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})")

MAC address (colon separator):

logscale
regex(regex="(?<mac>(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2})")

MAC address (hyphen separator):

logscale
regex(regex="(?<mac>(?:[0-9a-fA-F]{2}-){5}[0-9a-fA-F]{2})")

MAC address (either format):

logscale
regex(regex="(?<mac>(?:[0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2})")

Email address:

logscale
regex(regex="(?<email>[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})")

MD5 hash (32 hexadecimal characters):

logscale
regex(regex="(?<md5>\b[a-fA-F0-9]{32}\b)")

SHA1 hash (40 hexadecimal characters):

logscale
regex(regex="(?<sha1>\b[a-fA-F0-9]{40}\b)")

SHA256 hash (64 hexadecimal characters):

logscale
regex(regex="(?<sha256>\b[a-fA-F0-9]{64}\b)")

Generic hash with field name:

logscale
regex(regex="(?:md5|sha1|sha256|hash)[=:]?\s*(?<hash>[a-fA-F0-9]{32,64})")

This pattern matches hashes preceded by common field names like md5, sha1, sha256, or hash. The {32,64} quantifier matches hashes between 32 and 64 characters, covering MD5, SHA1, and SHA256.

Version Numbers

Extract version numbers from application logs.

Semantic version (1.2.3):

logscale
regex(regex="(?<version>\d+\.\d+\.\d+)")

Version with prefix (v2.4.1):

logscale
regex(regex="v(?<version>\d+\.\d+\.\d+)")

Integer part of decimal number:

logscale
regex(regex="(?<integer>\d+)\\..*", field=value)

Extracts only the digits before the decimal point from a decimal number. For example, from 3.14159, this pattern captures 3. The \\. matches the literal decimal point, and .* matches any remaining digits after it.

Error Codes and Identifiers

Extract error codes, identifiers, and structured codes from log messages.

Error code with prefix:

logscale
regex(regex="(?<error_code>ERR-\d+)", field=message)

Extracts error codes with a specific prefix pattern. This example matches codes like ERR-123, ERR-4567. Combine with a status code filter for targeted error analysis:

logscale
status = /^5\d{2}/
| regex(regex="(?<error_code>ERR-\d+)", field=message)

This filters for 5xx HTTP status codes, then extracts the error code from the message field.

Syslog and Encoded Data

Extract syslog-specific fields and encoded data.

Syslog priority (facility and severity):

logscale
regex(regex="<(?<priority>\d{1,3})>")

The priority value encodes both facility and severity. To extract them separately, use facility = priority / 8 and severity = priority % 8 after extraction.

Base64 encoded string:

logscale
regex(regex="(?<base64>[A-Za-z0-9+/]{20,}={0,2})")

This pattern matches Base64 strings of at least 20 characters (adjust {20,} as needed). The ={0,2} matches the optional padding at the end.

Key-Value Pairs

Extract key-value pairs from structured and semi-structured logs.

Key-value pairs (quoted or unquoted values):

logscale
regex(regex="(?<key>\w+)=(?<value>\"[^\"]*\"|\S+)")

This pattern extracts key-value pairs in formats like user="john doe" or status=active. The pattern components:

  • (?<key>\w+) captures the key name (word characters)

  • = matches the equals sign separator

  • (?<value>\"[^\"]*\"|\S+) captures the value in two formats:

    • \"[^\"]*\" matches quoted values with spaces (for example, "john doe")

    • |\S+ OR matches unquoted non-whitespace values (for example, active)

Use this pattern repeatedly to extract multiple key-value pairs from logs formatted as key1=value1 key2="value 2" key3=value3.

Extract Between Delimiters

Extract content between common delimiters.

Between square brackets:

logscale
regex(regex="\[(?<content>[^\]]+)\]")

Between double quotes:

logscale
regex(regex="\"(?<content>[^\"]+)\"")

Between parentheses:

logscale
regex(regex="\((?<content>[^\)]+)\)")

Between slash and at-sign (command line parsing):

logscale
regex(regex="/(?<command>[^@]+)@", field=CommandLine)

Extracts text between / and @ characters. Useful for parsing command line arguments or structured text with specific delimiters. The [^@]+ matches any character except @, capturing everything until the closing delimiter.

Between custom characters:

logscale
regex(regex="/\\\/(?<content>.*)@", field=CommandLine)

Extracts text between \/ and @. The pattern uses \\\/ to match the literal characters \/ (backslash-escaped forward slash), then captures everything with .* until reaching @. Adapt this pattern by replacing the start and end delimiters with your specific characters.

Complex Example: Apache Log Formats

These examples show how to parse Apache access logs using regex patterns. Apache supports two common log formats: Common Log Format (CLF) and Combined Log Format.

Apache Common Log Format (simpler):

logscale
regex(regex="(?<client_ip>[\d.]+) \S+ \S+ \[(?<req_time>[^\]]+)\] \"(?<method>\w+) (?<path>\S+) \S+\" (?<status>\d{3}) (?<bytes>\d+)")

This pattern extracts core fields from Apache Common Log Format:

192.168.1.100 - - [10/Oct/2023:13:55:36 -0700] "GET /api/users HTTP/1.1" 200 1234

Use this lighter pattern when you do not need referer or user agent information.

Apache Combined Log Format (comprehensive):

logscale
regex(regex="^(?<server_name>\S+) (?<client>\S+) \S+ (?<user_name>\S+) \[(?<timestamp>[^\]]+)\] \"(?<method>\S+) (?<url>\S+) HTTP/(?<http_version>[\d.]+)\" (?<status_code>\d{3}) (?<response_size>\d+) \"(?<referer>[^\"]*)\" \"(?<user_agent>[^\"]*)\"")

This pattern extracts all fields from Apache Combined Log Format, including referer and user agent:

example.com 192.168.1.100 - john [10/Oct/2023:13:55:36 -0700] "GET /api/users HTTP/1.1" 200 1234 "https://example.com/home" "Mozilla/5.0"

Pattern breakdown:

  • ^ anchors to the start of the line โ€” ensures the pattern matches from the beginning

  • (?<server_name>\S+) captures the server name โ€” \S+ matches one or more non-whitespace characters

  • (?<client>\S+) captures the client IP address โ€” uses \S+ to match the IP without spaces

  • \S+ matches the identity field (typically a dash) โ€” not captured because it is rarely used

  • (?<user_name>\S+) captures the authenticated username โ€” matches the username or a dash if not authenticated

  • \[(?<timestamp>[^\]]+)\] captures the timestamp โ€” [^\]]+ matches everything except the closing bracket, and the literal brackets are escaped with \[ and \]

  • \"(?<method>\S+) (?<url>\S+) HTTP/(?<http_version>[\d.]+)\" captures the HTTP request line components:

    • \" matches the opening quote (escaped)

    • (?<method>\S+) captures GET, POST, and so on

    • (?<url>\S+) captures the requested URL path

    • (?<http_version>[\d.]+) captures the HTTP version โ€” [\d.]+ matches digits and periods (for example, 1.1)

  • (?<status_code>\d{3}) captures the HTTP status code โ€” \d{3} matches exactly three digits

  • (?<response_size>\d+) captures the response size in bytes โ€” \d+ matches one or more digits

  • \"(?<referer>[^\"]*)\" captures the referer URL โ€” [^\"]* matches zero or more characters that are not quotes, allowing for empty referer fields

  • \"(?<user_agent>[^\"]*)\" captures the user agent string โ€” uses the same pattern as the referer to handle any characters within quotes

Key regex techniques demonstrated:

  • Named capture groups โ€” (?<name>pattern) extracts values into named fields

  • Character classes โ€” \S (non-whitespace), \d (digits), [^\]] (negated class: anything except closing bracket)

  • Quantifiers โ€” + (one or more), * (zero or more), {3} (exactly three)

  • Escaping special characters โ€” \" for literal quotes, \[ and \] for literal brackets

  • Anchoring โ€” ^ ensures the pattern starts at the beginning of the line

Complex Example: Structured Application Log Parsing

This example shows how to parse structured application logs that follow a consistent format with timestamp, log level, and message components.

Structured log regex:

logscale
regex(regex="(?<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (?<level>\w+) (?<message>.+)")

This pattern extracts fields from structured application logs in the format:

2024-03-15 14:32:01 ERROR Database connection failed: timeout after 30s
2024-03-15 14:32:05 INFO Retrying connection attempt 2 of 3
2024-03-15 14:32:10 WARN High memory usage detected: 87%

Pattern breakdown:

  • (?<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) captures the timestamp in YYYY-MM-DD HH:MM:SS format โ€” uses \d{4} for year, \d{2} for month, day, hour, minute, second

  • A space separates the timestamp from the log level

  • (?<level>\w+) captures the log level โ€” \w+ matches word characters (ERROR, INFO, WARN, DEBUG)

  • Another space separates the level from the message

  • (?<message>.+) captures the entire message โ€” .+ matches one or more of any character, capturing everything remaining on the line

This pattern works well for application logs that follow a consistent structure. After extraction, you can filter by log level, search within messages, or analyze patterns over time.

Antipatterns to Avoid

Common regex patterns that can cause performance issues or incorrect matches in LogScale.

Avoid: Greedy quantifiers with overlap

logscale
// BAD - causes excessive backtracking
regex(regex=".*error.*")

Instead, use non-greedy quantifiers or be more specific:

logscale
// BETTER - non-greedy
regex(regex=".*?error")

// BEST - specific pattern
regex(regex="\[(?<level>ERROR)\]")

Avoid: Back references

logscale
// BAD - back references are not supported efficiently
regex(regex="(\w+).*\1")

Back references like \1 cause performance issues. Find alternative approaches using field comparisons after extraction.

Avoid: Unnecessary wildcards at start and end

logscale
// BAD - implicit wildcard already exists
regex(regex="^.*error.*$")

LogScale implicitly adds .*? to patterns, so adding your own is redundant:

logscale
// BETTER - let LogScale handle the implicit wildcard
regex(regex="error")

Avoid: Overlapping character classes

logscale
// BAD - \w already includes digits
regex(regex="[\w\d]+")

// BETTER - use only what you need
regex(regex="\w+")

Avoid: Catastrophic backtracking patterns

logscale
// BAD - nested quantifiers cause exponential backtracking
regex(regex="(a+)+b")

// BETTER - simplify to single quantifier
regex(regex="a+b")

For more detailed guidance on avoiding regex pitfalls, see Best Practice: Regular Expressions and their Pitfalls.

Additional information

For more information about using regular expressions in LogScale, see: