C.W.K.
Stream
Lesson 11 of 12 · published

Code Patterns — Identifiers and Comments

~8 min · code-mods, identifiers

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Identifiers

Most languages: letter or underscore, then letters/digits/underscores.

[a-zA-Z_]\w*

For naming conventions:

  • camelCase: [a-z][a-zA-Z0-9]*
  • snake_case: [a-z][a-z0-9_]*
  • SCREAMING_SNAKE: [A-Z][A-Z0-9_]*
  • PascalCase: [A-Z][a-zA-Z0-9]*
  • kebab-case: [a-z][a-z0-9-]*

Comments

Single-line C-style: //[^\n]* or anchored ^//.*$ with MULTILINE.

Single-line shell/Python: #[^\n]* (watch for false positives — # in URLs, in strings).

Multi-line C-style: /\*[\s\S]*?\*/ — note [\s\S] instead of . to span newlines without DOTALL flag.

Real comment detection requires a tokenizer — comment-like patterns inside strings will false-positive. For source-code processing, use a real parser/AST when accuracy matters.

Code mods

Regex shines for refactoring across files: rename a function, change an import, restructure a config block. Use VS Code's regex find/replace or sed for one-shot mods. For complex refactors, AST tools (Python libcst, JS jscodeshift) are safer.

Code

Code regex examples·python
import re

# Identifier patterns
IDENT = re.compile(r'[a-zA-Z_]\w*')
re.findall(IDENT, 'function getUserById(user_id) {}')
# ['function', 'getUserById', 'user_id']

# camelCase only
CAMEL = re.compile(r'\b[a-z][a-zA-Z0-9]*\b')
re.findall(CAMEL, 'getUserById vs get_user_by_id')
# ['getUserById', 'get', 'user', 'by', 'id']  — splits snake_case

# Multi-line C-style comment
COMMENT = re.compile(r'/\*[\s\S]*?\*/')
re.findall(COMMENT, '/* hello */ code /* world */')
# ['/* hello */', '/* world */']

# Find imports in JavaScript
IMPORT = re.compile(
    r'^import\s+(?:\{[^}]+\}|\*\s+as\s+\w+|\w+)\s+from\s+[\'"]([^\'"]+)[\'"]',
    re.MULTILINE
)
code = '''
import React from 'react';
import { useState } from 'react';
import * as fs from 'fs';
'''
re.findall(IMPORT, code)
# ['react', 'react', 'fs']

External links

Exercise

Pick a function in your codebase. Use VS Code's regex find/replace to rename it across all its callers in one pass. Notice the false positives (occurrences in comments, in similar-named identifiers). Decide: is regex enough here, or do you need AST?

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.