Skip to content

regex

Pattern-matching expressions for extracting, replacing or validating text.

Matching Basics

Core patterns to match common text elements.

Single character match

Matches any single character except for line breaks.

Terminal window
\.
Matches any character before the newline. "a\nb".match(.) only matches "a"

String start anchor

Anchors the pattern to the beginning of a string.

Terminal window
^Hello
Matches "Hello" only if it's at the start of the line.

String end anchor

Anchors the pattern to the end of a string.

Terminal window
world$
Matches "world" only if it's at the end of the line.

Digit match

Matches any numeric digit (0-9).

Terminal window
\d
Matches any single digit like 0, 1, 2, ..., 9.

Non-digit match

Matches any character that is not a digit.

Terminal window
\D
Matches any character that is not a number, such as A, b, $, etc.

Whitespace match

Matches any whitespace character (space, tab, newline, etc.).

Terminal window
\s
Matches a space, tab, or newline character.

Non-whitespace match

Matches any character that is not whitespace.

Terminal window
\S
Matches any character that is not a space, tab, or newline.

Word character match

Matches letters (a-z, A-Z), numbers (0-9), and underscore (_).

Terminal window
\w
Matches any character a-z, A-Z, 0-9, and _.

Non-word character match

Matches any character that is not a word character.

Terminal window
\W
Matches any character that is not a-z, A-Z, 0-9, or _.

Newline match

Matches a newline character.

Terminal window
\n
Matches the line feed character (ASCII 10, often used to indicate the end of a line).

Character Sets & Ranges

Patterns to specify a set of allowable characters or ranges.

Specific character set

Matches any character within the specified set of characters.

Terminal window
[aeiou]
Matches any vowel.

Character range match

Matches characters within the specified range.

Terminal window
[a-z]
Matches any lowercase letter.

Excluded character set

Matches characters not in the specified set.

Terminal window
[^aeiou]
Matches any character that is not a vowel.

Character set or range

Matches any character that matches any of the patterns.

Terminal window
[a-zA-Z0-9_]
Matches any alphanumeric or underscore.

Quantifiers

Specify how many times a pattern must occur.

Zero or more occurrences

Matches the preceding pattern zero or more times.

Terminal window
*
Matches zero or more occurrences of the preceding character or group.

One or more occurrences

Matches the preceding pattern one or more times.

Terminal window
+
Matches one or more occurrences of the preceding character or group.

Zero or one occurrence

Matches the preceding pattern zero or one time.

Terminal window
\?
Matches zero or one occurrence of the preceding character or group.

Exact count repetition

Matches the preceding pattern an exact number of times.

Terminal window
{3}
Matches exactly 3 occurrences of the preceding character or group.

Range repetition count

Matches the preceding pattern within a range.

Terminal window
{2,5}
Matches between 2 and 5 occurrences (inclusive) of the preceding character or group.

Minimum repetition count

Matches the preceding pattern at least n times.

Terminal window
{2,}
Matches 2 or more occurrences of the preceding character or group.

Groups and Lookaheads

Advanced patterns for grouping and conditional matches.

Group patterns together

Groups multiple patterns to treat them as a single unit.

Terminal window
(abc)
Matches the sequence "abc".

Positive lookahead assertion

Matches a group if it is followed by another pattern (but doesn't consume it).

Terminal window
(?=abc)
Matches if the next characters are "abc", but the match pointer stays where it was.

Negative lookahead assertion

Matches a group if it is not followed by another pattern (but doesn't consume it).

Terminal window
(?!abc)
Matches if the next characters are NOT "abc".

Capture groups

Captures matched text for reference or replacement.

Terminal window
(group)
Captures the matched "group" in a numbered group.

Non-capturing group

Groups patterns without capturing the matched text.

Terminal window
(?:abc)
Groups "abc" but doesn't capture it.

Named capture group

Captures matched text with a name.

Terminal window
(?<name>group)
Captures the matched "group" with the name "name".

Positive lookbehind assertion

Matches a group if it is preceded by another pattern (but doesn't consume it).

Terminal window
(?<=abc)
Matches if the preceding characters are "abc".

Negative lookbehind assertion

Matches a group if it is not preceded by another pattern (but doesn't consume it).

Terminal window
(?<!abc)
Matches if the preceding characters are NOT "abc".

Escaping Special Characters

Handling characters that have special meanings in regex.

Escape special character

Matches the literal character instead of its special meaning.

Terminal window
\\

Literal dot match

Matches the literal '.' character.

Terminal window
\.

Literal asterisk match

Matches the literal '*' character.

Terminal window
*

Literal plus match

Matches the literal '+' character.

Terminal window
+

VS Code Find & Replace

Practical patterns for transforming real-world text with VS Code’s regex find and replace.

Move URLs to new lines

Extract URLs from lines and place each URL on a separate line.

Find
\s*(https?://.*)$
Replace
\n$1
Find
^(?!https?://).*$
Replace
""
Example
Some text https://example.com
Another line https://example.org/page
https://example.net

Convert matching lines to list

Add a list marker to every line containing a matching pattern.

Find
^(.*https?://.*)$
Replace
- $1
Example
https://example.com
https://example.org

Remove matching lines

Delete every complete line containing a specific pattern.

Find
^.*TODO:.*\r?\n?
Replace
""
Example
Keep this line
TODO: remove this line
Keep this too

Remove non-matching lines

Keep only lines that match a pattern and delete everything else.

Find
^(?!.*TODO:).*(?:\r?\n|$)
Replace
""
Example
Keep TODO: this item
Delete this line
Keep TODO: another item

Extract from parentheses

Replace each line with only the text contained inside parentheses.

Find
^.*\(([^()]*)\).*$
Replace
$1
Example
John Smith ([email protected])

Extract between delimiters

Replace each line with the text between two known delimiters.

Find
^.*\[(.*?)\].*$
Replace
$1
Example
Name: [Kevin]
Name: [Alex]

Wrap values in quotes

Find values matching a pattern and surround them with quotes.

Find
\b\d+\b
Replace
"$&"
Example
123
456
789

Add commas to multiline values

Add a comma to the end of every non-empty line for converting line-separated values into a list.

Find
^(.+)$
Replace
$1,
Example
apple
banana
orange

Convert to quoted list

Transform one value per line into quoted, comma-separated values.

Find
^(.+)$
Replace
"$1",
Example
apple
banana
orange

Swap two line values

Swap two delimiter-separated values using capture groups.

Find
^([^,]+),\s*(.+)$
Replace
$2, $1
Example
Smith, John
Doe, Jane

Reformat Last First names

Convert names from "Last, First" format to "First Last".

Find
^([^,]+),\s*(.+)$
Replace
$2 $1
Example
Smith, John
Doe, Jane

Indent matching lines

Add indentation to every line matching a specific pattern.

Find
^(import .+)$
Replace
" $1"
Example
import foo
const value = 1
import bar

Remove leading indentation

Remove all leading spaces and tabs from lines.

Find
^[ \t]+
Replace
""
Example
first line
second line
third line

Normalize trailing whitespace

Remove spaces and tabs from the ends of every line.

Find
[ \t]+$
Replace
""

Add blank lines between matches

Insert a blank line after every line matching a pattern.

Find
^(#+ .+)$
Replace
$1\n
Example
# Heading
Content
## Another heading
More content

Join wrapped lines

Join consecutive lines that belong to the same paragraph while preserving blank lines.

Find
(?<!\n)\n(?!\n)
Replace
" "

Convert HTML attributes

Replace an HTML attribute value while preserving the surrounding tag.

Find
(<img\b[^>]*\bsrc=")[^"]*(")
Replace
$1/new/path/image.jpg$2
Example
<img src="/old/path/image.jpg" alt="Example">

Rename HTML attribute

Rename an attribute everywhere while preserving its value.

Find
\bdata-old="([^"]*)"
Replace
data-new="$1"
Example
<div data-old="123">
<span data-old="456">

Replace Markdown links with only their destination URLs.

Find
\[([^\]]+)\]\((https?://[^)]+)\)
Replace
$2
Example
[Google](https://google.com)
[YouTube](https://youtube.com)

Convert Markdown links into HTML anchor elements.

Find
\[([^\]]+)\]\((https?://[^)]+)\)
Replace
<a href="$2">$1</a>
Example
[Google](https://google.com)

Keep the visible link text while removing the Markdown destination.

Find
\[([^\]]+)\]\([^)]+\)
Replace
$1
Example
[Google](https://google.com)
[Example](https://example.com)

Convert Markdown headings

Convert Markdown headings into HTML heading elements while preserving heading levels and text.

Find
^#{1,6}\s+(.+)$
Replace
"<h$#>$1</h$#>"
VS Code replacement syntax cannot dynamically reuse the number of

Find duplicate lines

Find repeated complete lines so duplicates can be reviewed or removed.

^(.+)(?:\r?\n\1)+$
Example
apple
banana
apple
orange

Find duplicate adjacent values

Find repeated words or values appearing consecutively.

\b(\w+)\s+\1\b
Example
very very important

Find repeated case-insensitive words

Find consecutive duplicate words regardless of capitalization.

\b([A-Za-z]+)\s+\1\b
Example
The the quick brown fox

Find multi-pattern lines

Find lines that contain both required patterns without caring about their order.

^(?=.*foo)(?=.*bar).*$
Example
foo and bar appear on this line

Find lines missing pattern

Find complete lines that do not contain a required pattern.

^(?!.*foo).*$
Example
foo is present
this line does not contain it

Find values with surrounding whitespace

Find a value while capturing its meaningful content and excluding surrounding whitespace.

^\s*(.*?)\s*$
Example
some value

Replace first occurrence per line

Replace the first occurrence of a pattern on each line while leaving later occurrences unchanged.

Find
^(.*?)foo
Replace
$1bar
Example
foo foo foo

Replace after delimiter

Preserve the beginning of each line and replace everything after a known delimiter.

Find
^([^:]+):.*$
Replace
$1: new value
Example
name: old value
status: old value

Replace before delimiter

Preserve the end of each line and replace everything before a known delimiter.

Find
^.*:\s*(.+)$
Replace
new key: $1
Example
old key: value
another key: value

Extract file extensions

Replace filenames with only their final file extension.

Find
^.*\.([^.]+)$
Replace
$1
Example
image.png
document.pdf
archive.tar.gz

Change file extensions

Replace the extension of every matching filename while preserving the filename.

Find
^(.+)\.[^.]+$
Replace
$1.webp
Example
image.png
photo.jpg
graphic.gif

Convert kebab-case to camelCase

Convert hyphenated words into camelCase using a capture group.

Find
-([a-z])
Replace
\u$1
Example
my-component-name

Convert snake_case to camelCase

Convert underscore-separated words into camelCase.

Find
_([a-z])
Replace
\u$1
Example
my_component_name

Remove line comments

Remove inline comments while preserving the content before the comment marker.

Find
^(.*?)(?:\s*#.*)?$
Replace
$1
Example
command --option value

Extract quoted strings

Find and capture text enclosed in single or double quotes.

(["'])(.*?)\1
Example
"hello world"
'another value'

Find TODO or FIXME lines

Find development notes such as TODO and FIXME regardless of capitalization.

^.*\b(?:TODO|FIXME)\b.*$
Example
// TODO: refactor this
// FIXME: handle error case

Find empty lines

Find lines that contain no meaningful characters.

^\s*$

Collapse multiple blank lines

Replace runs of multiple blank lines with a single blank line.

Find
(?:\r?\n\s*){3,}
Replace
\n\n

Add newline after delimiters

Split a single-line list into separate lines after a delimiter.

Find
,\s*
Replace
\n
Example
apple, banana, orange

Split key-value pairs

Split semicolon-separated key-value pairs onto separate lines.

Find
;\s*
Replace
\n
Example
name=Kevin;role=developer;active=true

Extract URLs from text

Find HTTP and HTTPS URLs embedded anywhere in text.

https?://[^\s<>"')]+
Example
Visit https://example.com/path?q=1 for details.

Find email addresses

Find common email address patterns embedded in text.

\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b
Example
Contact [email protected] for help.

Find version numbers

Find semantic-style version numbers such as 1.2.3 or 2.0.0-beta.

\b\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?\b
Example
version 2.4.1-beta.3

Find ISO dates

Find dates formatted as YYYY-MM-DD.

\b\d{4}-\d{2}-\d{2}\b
Example
Published on 2026-08-10.

Find hex colors

Find three- or six-digit hexadecimal color values.

\B#[0-9A-Fa-f]{3}(?:[0-9A-Fa-f]{3})?\b
Example
color: #fff; background: #1a2b3c

Find CSS declarations

Capture CSS property names and values for bulk editing.

^\s*([A-Za-z-]+)\s*:\s*([^;]+);?
Example
color: #fff;

Find JSON keys

Find quoted JSON property names while preserving their names for replacement.

^[ \t]*"([^"\\]+)"\s*:
Example
"name": "Kevin",
"email": "[email protected]",

Convert JSON keys

Rename JSON keys while leaving their values untouched.

Find
(^\s*)"oldName"(\s*:)
Replace
$1"newName"$2
Example
{
"oldName": "value"
}

Wrap lines in tags

Wrap every complete line in a consistent opening and closing tag.

Find
^(.+)$
Replace
<item>$1</item>
Example
First
Second
Third

Prefix matching lines

Add a prefix only to lines containing a specific pattern.

Find
^(?=.*error)(.*)$
Replace
"ERROR: $1"
Example
request succeeded
request error occurred
another error

Suffix matching lines

Add a suffix only to lines containing a specific pattern.

Find
^(?=.*TODO)(.*)$
Replace
"$1 <!-- review -->"
Example
TODO: update documentation
completed task

Capture text before delimiter

Capture everything before the first occurrence of a delimiter.

^([^:]+):
Example
name: Kevin

Capture text after delimiter

Capture everything after the first occurrence of a delimiter.

:\s*(.*)$
Example
name: Kevin

Match basic parentheses

Match simple parenthesized content when nested parentheses are not required.

\([^()]*\)
Example
Function (argument value)

Match content between HTML tags

Capture the content inside a specific HTML element.

<p\b[^>]*>(.*?)</p>
Example
<p>This is the content.</p>

Remove HTML tags

Strip simple HTML tags while preserving their text content.

Find
<[^>]+>
Replace
""

Convert line endings

Normalize Windows CRLF line endings to LF.

Find
\r\n
Replace
\n

Find trailing punctuation lines

Find lines ending with punctuation that can be removed or replaced.

^(.+?)[,;:]+$
Example
first;
second,
third:

Remove trailing punctuation

Remove commas, semicolons, or colons from the ends of lines.

Find
^(.+?)[,;:]+$
Replace
$1

Find numeric values with units

Capture a number and its unit separately for bulk conversion or editing.

\b(\d+(?:\.\d+)?)\s*(px|em|rem|%|vh|vw)\b
Example
width: 24px
margin: 1.5rem
height: 50vh

Find function calls

Capture function names and their arguments for bulk code transformations.

\b([A-Za-z_$][\w$]*)\(([^()]*)\)
Example
console.log("hello")

Convert function syntax

Transform simple function calls using captured function names and arguments.

Find
\b([A-Za-z_$][\w$]*)\(([^()]*)\)
Replace
$1[$2]
Example
foo(bar)
baz(qux)

Find package imports

Find JavaScript or TypeScript imports originating from a specific package.

^import\s+.*\s+from\s+["']some-package["'];?$
Example
import { foo } from "some-package";

Find TODO comments

Find TODO comments while capturing the message for review or extraction.

\bTODO\b[:\s]*(.+)$
Example
// TODO: replace this implementation

Find unmatched quotes

Find lines containing an odd number of double quotes, useful for locating malformed quoted values.

^(?:[^"]*"[^"]*")*[^"]*"[^"]*$
Example
name: "Kevin

Match repeated separators

Find runs of repeated punctuation that can be normalized.

([|,_-])\1+
Example
foo---bar___baz

Normalize repeated separators

Replace repeated separators with a single separator.

Find
([|,_-])\1+
Replace
$1
Example
foo---bar___baz

Find delimiter surrounding whitespace

Find inconsistent whitespace surrounding commas, colons, or equals signs.

\s*([,:=])\s*
Example
name : Kevin

Normalize delimiter spacing

Normalize whitespace around a delimiter while preserving the delimiter.

Find
\s*([,:=])\s*
Replace
$1
Example
name : Kevin

Extract frontmatter fields

Capture the value of a specific YAML frontmatter field.

^title:\s*(.+)$
Example
title: My Cheatsheet

Replace frontmatter field

Replace the value of a specific YAML frontmatter field without changing the field name.

Find
^(title:\s*).+$
Replace
$1New Title
Example
title: Old Title

Find multiline blocks

Match a block beginning with one marker and ending at the next marker using a lazy match.

^START$[\s\S]*?^END$
Example
START
content
more content
END

Remove multiline blocks

Delete complete blocks between explicit START and END markers.

Find
^START$[\s\S]*?^END$\r?\n?
Replace
""

Find repeated delimiter content

Capture content between matching delimiter characters such as triple backticks.

```([\s\S]*?)```
Example
```
code here
```

Extract Markdown code blocks

Capture the contents of fenced Markdown code blocks without the surrounding fences.

^```(?:\w+)?\r?\n([\s\S]*?)^```$
Example
```ts
const value = 1;
```

Convert code fences

Replace fenced code blocks with another delimiter while preserving their contents.

Find
^```(?:\w+)?\r?\n([\s\S]*?)^```$
Replace
<pre>$1</pre>

Move captured text to new line

Capture part of each line and move it onto its own line.

Find
^(.*?)(\s+)(https?://\S+)$
Replace
$1\n$3
Example
Visit https://example.com
Documentation https://example.org/docs

Keep URL matching lines

Delete every line that does not begin with an HTTP or HTTPS URL.

Find
^(?!https?://).*(?:\r?\n|$)
Replace
""
Example
https://example.com
Some unrelated text
https://example.org

Extract URLs into clean list

Extract URLs from arbitrary lines, then remove the surrounding text and preserve one URL per line.

Find
^.*?(https?://\S+).*$
Replace
$1
Example
Website: https://example.com
Docs: https://example.org/docs

Find pattern beginning lines

Find complete lines beginning with one of several alternatives.

^(?:ERROR|WARN|INFO)\b.*$
Example
INFO Application started
WARN Cache expired
DEBUG Request received

Find pattern ending lines

Find complete lines ending with one of several alternatives.

^.*(?:\.js|\.ts|\.tsx)$
Example
src/index.ts
src/app.tsx
README.md

Replace selected file extensions

Change only specified extensions while preserving the filename.

Find
^(.+)\.(?:js|jsx|ts)$
Replace
$1.mjs
Example
app.js
component.jsx
server.ts
README.md

Add extension to extensionless files

Add a file extension to matching filenames that do not already have one.

Find
^([^./]+)$
Replace
$1.txt
Example
README
LICENSE
notes

Find active TODOs

Find TODO markers that are not immediately followed by a completed status.

^(?!.*TODO\s*DONE).*TODO.*$
Example
TODO: fix this
TODO DONE: already handled

Find deprecated API usage

Find calls to a deprecated function while avoiding comments and unrelated identifiers.

\bdeprecatedFunction\s*\(
Example
deprecatedFunction(value)

Find prefixed quoted values

Find quoted strings whose contents begin with a known prefix.

["'](?:https?://)[^"']+["']
Example
url: "https://example.com"

Find non-matching format values

Find lines whose entire value does not match a required format.

^(?!\d{4}-\d{2}-\d{2}$).+$
Example
2026-08-10
08/10/2026
2026-8-10