Skip to content

regex

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

Matching Basics

Core patterns to match common text elements.

Match any single character (except newline)

A pattern that matches any single character except for line breaks.

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

Match the start of a string

Anchors the pattern to the beginning of a string.

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

Match the end of a string

Anchors the pattern to the end of a string.

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

Match any digit

Matches any numeric digit (0-9).

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

Match any non-digit

Matches any character that is not a digit.

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

Match any whitespace character

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

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

Match any non-whitespace character

Matches any character that is not whitespace.

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

Match a word character

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

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

Match a non-word character

Matches any character that is not a word character.

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

Match any newline

Matches a newline character.

\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.

Match a specific character set

Matches any character within the specified set of characters.

\[aeiou\]
Matches any vowel.

Match a range of characters

Matches characters within the specified range.

\[a-z\]
Matches any lowercase letter.

Match any character except specified ones

Matches characters not in the specified set.

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

Match a character from a set or range

Matches any character that matches any of the patterns.

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

Quantifiers

Specify how many times a pattern must occur.

Match zero or more times

Matches the preceding pattern zero or more times.

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

Match one or more times

Matches the preceding pattern one or more times.

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

Match zero or one time

Matches the preceding pattern zero or one time.

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

Match a specific number of times

Matches the preceding pattern an exact number of times.

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

Match a range of times

Matches the preceding pattern within a range.

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

Match at least n times

Matches the preceding pattern at least n times.

\{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.

(abc)
Matches the sequence "abc".

Positive lookahead

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

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

Negative lookahead

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

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

Capture groups

Captures matched text for reference or replacement.

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

Non-capturing group

Groups patterns without capturing the matched text.

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

Named capture group

Captures matched text with a name.

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

Positive lookbehind

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

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

Negative lookbehind

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

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

Escaping Special Characters

Handling characters that have special meanings in regex.

Escape a special character

Matches the literal character instead of its special meaning.

\\

Match a literal dot

Matches the literal '.' character.

\.

Match a literal asterisk

Matches the literal '*' character.

\*

Match a literal plus sign

Matches the literal '+' character.

\+

VS Code Find & Replace

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

Move URLs to their own lines

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

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

Convert matching lines into a list

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

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

Remove lines matching a pattern

Delete every complete line containing a specific pattern.

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

Remove everything except matching lines

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

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

Extract text from parentheses

Replace each line with only the text contained inside parentheses.

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

Extract text between delimiters

Replace each line with the text between two known delimiters.

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

Wrap matching values in quotes

Find values matching a pattern and surround them with quotes.

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

Add commas to multiline values

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

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

Convert lines into a quoted list

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

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

Swap two values on each line

Swap two delimiter-separated values using capture groups.

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

Convert Last, First names

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

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

Add indentation to matching lines

Add indentation to every line matching a specific pattern.

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

Remove leading indentation

Remove all leading spaces and tabs from lines.

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

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.

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

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.

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

Rename an HTML attribute

Rename an attribute everywhere while preserving its value.

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

Convert Markdown links to URLs

Replace Markdown links with only their destination URLs.

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

Convert Markdown links to HTML

Convert Markdown links into HTML anchor elements.

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

Remove Markdown link formatting

Keep the visible link text while removing the Markdown destination.

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

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.

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

Find duplicate adjacent values

Find repeated words or values appearing consecutively.

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

Find repeated words ignoring case

Find consecutive duplicate words regardless of capitalization.

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

Find lines containing multiple patterns

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

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

Find lines missing a pattern

Find complete lines that do not contain a required pattern.

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

Find values with surrounding whitespace

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

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

Replace only the first occurrence per line

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

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

Replace everything after a delimiter

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

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

Replace everything before a delimiter

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

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

Extract file extensions

Replace filenames with only their final file extension.

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

Change file extensions

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

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

Convert kebab-case to camelCase

Convert hyphenated words into camelCase using a capture group.

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

Convert snake_case to camelCase

Convert underscore-separated words into camelCase.

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

Remove comments from lines

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

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

Extract quoted strings

Find and capture text enclosed in single or double quotes.

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

Find TODO or FIXME lines

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

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

Find empty or whitespace-only 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 a newline after delimiters

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

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

Split key-value pairs into lines

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

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

Extract URLs from arbitrary text

Find HTTP and HTTPS URLs embedded anywhere in text.

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

Find email addresses

Find common email address patterns embedded in text.

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

Find version numbers

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

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

Find ISO dates

Find dates formatted as YYYY-MM-DD.

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

Find hex colors

Find three- or six-digit hexadecimal color values.

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

Find CSS declarations

Capture CSS property names and values for bulk editing.

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

Find JSON keys

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

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

Convert JSON keys to another name

Rename JSON keys while leaving their values untouched.

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

Wrap selected lines in tags

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

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

Prefix matching lines

Add a prefix only to lines containing a specific pattern.

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

Suffix matching lines

Add a suffix only to lines containing a specific pattern.

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

Capture text before a delimiter

Capture everything before the first occurrence of a delimiter.

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

Capture text after a delimiter

Capture everything after the first occurrence of a delimiter.

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

Match balanced-looking parentheses

Match simple parenthesized content when nested parentheses are not required.

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

Match text between HTML tags

Capture the content inside a specific HTML element.

<p>This is the content.</p>
<p\b[^>]*>(.*?)</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 lines with trailing punctuation

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

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.

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

Find function calls

Capture function names and their arguments for bulk code transformations.

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

Convert function syntax

Transform simple function calls using captured function names and arguments.

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

Find imports from a package

Find JavaScript or TypeScript imports originating from a specific package.

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

Find TODO comments across files

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

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

Find lines with unmatched quotes

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

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

Match repeated separators

Find runs of repeated punctuation that can be normalized.

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

Normalize repeated separators

Replace repeated separators with a single separator.

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

Find whitespace around delimiters

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

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

Normalize delimiter spacing

Normalize whitespace around a delimiter while preserving the delimiter.

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

Extract Markdown frontmatter fields

Capture the value of a specific YAML frontmatter field.

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

Replace a frontmatter field

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

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

Find multiline blocks

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

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

Remove multiline blocks

Delete complete blocks between explicit START and END markers.

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

Find content between repeated delimiters

Capture content between matching delimiter characters such as triple backticks.

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

Extract Markdown code blocks

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

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

Convert Markdown 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 a new line

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

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

Keep only lines matching a URL

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

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

Extract URLs into a clean list

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

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

Find lines beginning with a pattern

Find complete lines beginning with one of several alternatives.

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

Find lines ending with a pattern

Find complete lines ending with one of several alternatives.

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

Replace selected file extensions

Change only specified extensions while preserving the filename.

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

Add extensions to extensionless files

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

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

Find TODOs excluding completed items

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

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

Find deprecated API usage

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

deprecatedFunction(value)
\bdeprecatedFunction\s*\(

Find quoted values with a specific prefix

Find quoted strings whose contents begin with a known prefix.

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

Find values not matching a format

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

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