Real-World Regex Applications

Regex isn’t just for log parsing. These patterns apply to every aspect of your digital life.

Professional Work

ISE & 802.1X Authentication

Pattern Regex (ERE) Use Case

Session ID

Session[0-9a-f]{8}/:[0-9]

Extract session identifiers

MAC Address (Cisco format)

([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}

Find endpoint MACs in logs

Authentication result

(PASS|FAIL):[A-Za-z0-9-]+

Filter auth outcomes

Posture status

(Compliant|NonCompliant|Unknown)

Track compliance states

RADIUS attribute

=".?"

Extract RADIUS AVPs

ISE Log Analysis Commands
# Find all authentication failures
grep -E 'AuthenticationFailed|Authentication failed' ise-logs.txt

# Extract unique MAC addresses that failed auth
grep -oE '([0-9A-Fa-f]\{2}:)\{5}[0-9A-Fa-f]\{2}' auth-failures.log | sort -u

# Find RADIUS Reject reasons
grep -oP '(?<=Reject-Reason=")[^"]+' radius.log

# Extract session IDs from failed authentications
grep -E 'FAIL' ise.log | grep -oE 'Session[0-9a-f]\{8}/[0-9]+:[0-9]+'

# Count failures per endpoint
grep -oE '([0-9A-Fa-f]\{2}:)\{5}[0-9A-Fa-f]\{2}' failures.log | sort | uniq -c | sort -rn

Network Infrastructure

Pattern Regex (ERE) Use Case

IPv4 Address

\b([0-9]\{1,3}\.){3}[0-9]\{1,3}\b

Extract IPs from configs

IPv4 with CIDR

([0-9]\{1,3}\.){3}[0-9]\{1,3}/[0-9]\{1,2}

Find subnet definitions

VLAN ID

[Vv][Ll][Aa][Nn]\s*[0-9]\{1,4}

Extract VLAN references

Interface name

(Gi|Te|Fa|Eth)(/[0-9])*

Find interface references

Port number

:[0-9]\{1,5}\b

Extract service ports

ASN

AS[0-9]\{1,10}

BGP autonomous system numbers

Network Config Analysis
# Find all subnets in config
grep -oE '([0-9]\{1,3}\.)\{3}[0-9]\{1,3}/[0-9]\{1,2}' router.conf

# Extract interface configurations
grep -E '^interface (Gi|Te|Fa)' switch.conf

# Find ACL permit/deny statements
grep -E '(permit|deny)\s+(ip|tcp|udp)' firewall.conf

# List all ports mentioned
grep -oE ':[0-9]\{1,5}' config.txt | sort -t: -k2 -n | uniq

# Find OSPF area definitions
grep -oE 'area [0-9]+' ospf.conf | sort -u

Security Analysis

Pattern Regex (PCRE) Use Case

SSH key fingerprint

SHA256:[A-Za-z0-9+/]{43}

Validate key fingerprints

Certificate CN

CN=([^,/]+)

Extract certificate subjects

JWT token

eyJ[A-Za-z0-9_-]\.eyJ[A-Za-z0-9_-]\.[A-Za-z0-9_-]+

Find JWTs in logs

Base64 encoded

[A-Za-z0-9+/]\{20,}=\{0,2}

Detect encoded data

Password pattern

(password|passwd|pwd|secret)[=:]\s*\S+

Find exposed credentials

API key format

[A-Za-z0-9_-]\{32,64}

Detect API keys

Security Audit Commands
# Find potential secrets in code
grep -rP '(password|secret|api_key|token)\s*[=:]\s*["\047][^"\047]+' src/

# Extract certificate subjects
openssl x509 -in cert.pem -noout -subject | grep -oP 'CN=\K[^,/]+'

# Find hardcoded IPs
grep -rE '\b([0-9]\{1,3}\.)\{3}[0-9]\{1,3}\b' --include="*.py" src/

# Detect base64 strings (potential secrets)
grep -oE '[A-Za-z0-9+/]\{40,}=\{0,2}' config.yaml

# Find sudo commands in logs
grep -E 'sudo.*COMMAND=' /var/log/auth.log

Log Analysis

Pattern Regex Use Case

ISO timestamp

[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}

Match standard timestamps

Syslog timestamp

[A-Z][a-z]{2}\s+[0-9]\{1,2}\s+[0-9]{2}:[0-9]{2}:[0-9]{2}

Match syslog format

Log level

\[(INFO|WARN|ERROR|DEBUG|FATAL)\]

Filter by severity

Error with context

[Ee]rror.:.$

Capture error messages

HTTP status code

" [0-9]{3} "

Extract HTTP responses

Response time

(\.[0-9])?\s*(ms|s)\b

Find latency values

Log Analysis Commands
# Count errors by type
grep -oE 'ERROR: [A-Za-z]+' app.log | sort | uniq -c | sort -rn

# Find slow requests (>1000ms)
grep -P '\d\{4,}ms' access.log

# Extract 5xx errors
grep -E '" 5[0-9]\{2} "' access.log

# Find failed SSH attempts
grep -E 'Failed password' /var/log/auth.log | tail -20

# Extract usernames from auth logs
grep -oP '(?<=for )\w+(?= from)' /var/log/auth.log | sort | uniq -c

Personal Life Applications

Note Organization

Pattern Regex Use Case

TODO items

TODO:.*$

Find action items

Questions

\?[^?]*$

Find questions asked

Dates mentioned

(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+[0-9]\{1,2}

Extract date references

People mentions

@[A-Za-z]+

Find person references

Tags

#[A-Za-z0-9_-]+

Extract hashtags

Links

https?://[^\s]+

Find URLs

Note Search Commands
# Find all TODOs across notes
grep -rE 'TODO:|FIXME:|NOTE:' ~/notes/

# Find unanswered questions
grep -rE '\?$' ~/notes/ --include="*.md" --include="*.adoc"

# Extract all tags used
grep -roE '#[A-Za-z0-9_-]+' ~/notes/ | cut -d: -f2 | sort | uniq -c | sort -rn

# Find mentions of specific person
grep -ri '@gabriel\|@sarah' ~/notes/

# List all external links
grep -ohE 'https?://[^\s)]+' ~/notes/*.md | sort -u

Journal & Reflections

Pattern Regex Use Case

Gratitude entries

(grateful|thankful|appreciate).*$

Find gratitude mentions

Goals mentioned

(goal|objective|want to|plan to).*$

Extract goal statements

Accomplishments

(completed|finished|achieved|accomplished).*$

Find wins

Challenges

(struggle|difficult|challenge|problem).*$

Find areas of difficulty

Mood indicators

(happy|sad|anxious|excited|frustrated|calm)

Track emotional states

Journal Analysis Commands
# Find gratitude entries this month
grep -ri 'grateful\|thankful' ~/journal/2026-03-*

# Extract goal statements
grep -riE '(i want to|i will|my goal|planning to)' ~/journal/

# Count positive vs negative entries
echo "Positive: $(grep -riEc 'happy|excited|grateful|accomplished' ~/journal/)"
echo "Challenges: $(grep -riEc 'struggle|difficult|frustrated|anxious' ~/journal/)"

# Find entries mentioning specific people
grep -rin 'gabriel\|sarah' ~/journal/2026-*

Financial Tracking

Pattern Regex Use Case

Dollar amounts

\$[0-9]\{1,3}(,[0-9]{3})*(\.[0-9]{2})?

Extract monetary values

Percentage

(\.[0-9])?%

Find percentages

Account numbers

[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}

Detect card numbers (to redact)

Transaction date

[0-9]{2}/[0-9]{2}/[0-9]{4}

Extract US date format

Category prefix

(rent|utilities|groceries|dining|transport):

Find categorized expenses

Financial Analysis Commands
# Find all dollar amounts
grep -oE '\$[0-9,]+(\.[0-9]\{2})?' expenses.txt

# Sum expenses (requires awk)
grep -oE '\$[0-9,]+(\.[0-9]\{2})?' expenses.txt | \
  sed 's/[$,]//g' | awk '{sum+=$1} END {print "$"sum}'

# Find recurring expenses
grep -E '(monthly|recurring|subscription)' budget.md

# Detect and mask card numbers
sed -E 's/[0-9]\{4}[- ]?[0-9]\{4}[- ]?[0-9]\{4}[- ]?[0-9]\{4}/****-****-****-****/g' file.txt

Health & Fitness

Pattern Regex Use Case

Weight entry

[0-9]\{2,3}(\.[0-9])?\s*(lbs?|kg)

Extract weight logs

Workout duration

[0-9]+\s*(min|minutes|hrs?|hours)

Find exercise duration

Sleep time

([0-9]\{1,2}(\.[0-9])?)\s*hours?\s*(sleep|slept)

Track sleep

Steps count

[0-9,]+\s*steps

Extract step counts

Medication

(took|take)\s+(\s[0-9]+\s*mg)?

Track medication

Health Log Commands
# Extract weight entries
grep -oE '[0-9]\{2,3}(\.[0-9])? ?(lbs?|kg)' health-log.txt

# Find workout entries
grep -E '(workout|exercise|gym|run|walk)' ~/journal/2026-*

# Calculate average sleep (last 7 days)
grep -oE '[0-9]+(\.[0-9])? hours? sleep' ~/journal/*.md | \
  grep -oE '[0-9]+(\.[0-9])?' | \
  awk '{sum+=$1; count++} END {print sum/count " hours avg"}'

Time Management

Pattern Regex Use Case

Time block

[0-9]\{1,2}:[0-9]{2}\s*-\s*[0-9]\{1,2}:[0-9]{2}

Find time ranges

Duration

[0-9]+h\s*[0-9]*m?

Parse durations

Meeting time

(meeting|call|sync)\s+@?\s*[0-9]\{1,2}(:[0-9]{2})?\s*(am|pm)?

Extract meeting times

Deadline

(due|deadline|by)\s+\s[0-9]\{1,2}

Find deadlines

Pomodoro

(pomodoro|pom)[^0-9]*[0-9]+

Track pomodoro sessions

Time Tracking Commands
# Find time blocks in schedule
grep -oE '[0-9]\{1,2}:[0-9]\{2}\s*-\s*[0-9]\{1,2}:[0-9]\{2}' schedule.md

# Extract meeting mentions
grep -E '(meeting|call|sync|standup)' ~/calendar/*.ics

# Find deadlines
grep -riE '(due|deadline|by) (jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)' ~/notes/

# Calculate daily coding time (from time logs)
grep -E 'code|programming|dev' time-log.txt | \
  grep -oE '[0-9]+h' | sed 's/h//' | awk '{sum+=$1} END {print sum "h total"}'

Contact & Communication

Pattern Regex Use Case

Email address

@[A-Za-z0-9.-]\.[A-Za-z]\{2,}

Extract emails

Phone (US)

\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}

Find phone numbers

Name format

[A-Z]\s[A-Z][a-z]+

Find full names

Follow-up mention

(follow[ -]?up|reach out|contact|email)\s+\w+

Find follow-up tasks

Contact Search Commands
# Extract all email addresses from notes
grep -rohE '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]\{2,}' ~/notes/ | sort -u

# Find phone numbers
grep -oE '\(?[0-9]\{3}\)?[-. ]?[0-9]\{3}[-. ]?[0-9]\{4}' contacts.txt

# Find pending follow-ups
grep -ri 'follow.?up\|reach out\|need to contact' ~/notes/ ~/journal/

Tool-Specific Workflows

grep - Search & Extract

# Search recursively with file type filter
grep -rE 'pattern' --include="*.py" --include="*.sh" src/

# Count matches per file
grep -rc 'ERROR' logs/*.log | grep -v ':0$'

# Show context around matches
grep -C 3 'Exception' app.log

# Inverse match (lines NOT matching)
grep -v '^#' config.conf  # Remove comments

sed - Transform

# Replace in place
sed -i 's/old/new/g' file.txt

# Delete lines matching pattern
sed '/^#/d' config.conf > clean.conf

# Extract between patterns
sed -n '/START/,/END/p' file.txt

# Multiple substitutions
sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt

awk - Analyze

# Extract specific field
awk -F: '{print $1}' /etc/passwd

# Filter and sum
awk '$3 > 100 {sum += $3} END {print sum}' data.txt

# Pattern matching with action
awk '/ERROR/ {count++} END {print count}' log.txt

# Field extraction with regex
awk 'match($0, /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/) {print substr($0, RSTART, RLENGTH)}' log.txt

vim - Edit

" Search with magic mode (ERE-like)
/\v\d\{1,3}\.\d\{1,3}\.\d\{1,3}\.\d\{1,3}

" Global substitute
:%s/old/new/g

" Delete lines matching pattern
:g/^#/d

" Extract matches to register
:let @a='' | g/pattern/y A

Python re - Script

import re

text = open('log.txt').read()

# Find all
ips = re.findall(r'\d\{1,3}\.\d\{1,3}\.\d\{1,3}\.\d\{1,3}', text)

# Search with groups
match = re.search(r'user=(\w+)', text)
if match:
    username = match.group(1)

# Replace
clean = re.sub(r'password=\S+', 'password=***', text)

# Named groups
pattern = r'(?P<date>\d\{4}-\d\{2}-\d\{2}) (?P<level>\w+) (?P<msg>.*)'
for match in re.finditer(pattern, text):
    print(match.groupdict())

Pattern Library

Quick Copy Patterns

Table 1. Copy-Paste Ready
What Pattern

IPv4

([0-9]\{1,3}\.){3}[0-9]\{1,3}

MAC (colon)

([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}

Email

@[A-Za-z0-9.-]\.[A-Za-z]\{2,}

URL

https?://[\s<>"{}|\\]+

ISO Date

[0-9]{4}-[0-9]{2}-[0-9]{2}

ISO Timestamp

[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}

Dollar Amount

\$[0-9]\{1,3}(,[0-9]{3})*(\.[0-9]{2})?

Phone (US)

\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}

UUID

[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}

Username

@[A-Za-z][A-Za-z0-9_]+

Hashtag

#[A-Za-z][A-Za-z0-9_]+

Practice Exercises

Professional Exercise Set

  1. ISE Log Mining: Extract all unique MAC addresses that failed authentication

  2. Network Audit: Find all interfaces configured with trunk mode

  3. Security Scan: Detect potential hardcoded passwords in config files

  4. Performance: Find all requests taking >500ms from access logs

Personal Exercise Set

  1. Note Audit: Find all TODO items across your notes directory

  2. Financial: Extract and sum all dollar amounts from expense reports

  3. Journal: Find entries mentioning specific goals or achievements

  4. Contacts: Build a list of all email addresses mentioned in your notes