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.
\.String start anchor
Anchors the pattern to the beginning of a string.
^HelloString end anchor
Anchors the pattern to the end of a string.
world$Digit match
Matches any numeric digit (0-9).
\dNon-digit match
Matches any character that is not a digit.
\DWhitespace match
Matches any whitespace character (space, tab, newline, etc.).
\sNon-whitespace match
Matches any character that is not whitespace.
\SWord character match
Matches letters (a-z, A-Z), numbers (0-9), and underscore (_).
\wNon-word character match
Matches any character that is not a word character.
\WNewline match
Matches a newline character.
\nCharacter Sets & Ranges
Patterns to specify a set of allowable characters or ranges.
Specific character set
Matches any character within the specified set of characters.
[aeiou]Character range match
Matches characters within the specified range.
[a-z]Excluded character set
Matches characters not in the specified set.
[^aeiou]Character set or range
Matches any character that matches any of the patterns.
[a-zA-Z0-9_]Quantifiers
Specify how many times a pattern must occur.
Zero or more occurrences
Matches the preceding pattern zero or more times.
*One or more occurrences
Matches the preceding pattern one or more times.
+Zero or one occurrence
Matches the preceding pattern zero or one time.
\?Exact count repetition
Matches the preceding pattern an exact number of times.
{3}Range repetition count
Matches the preceding pattern within a range.
{2,5}Minimum repetition count
Matches the preceding pattern at least n times.
{2,}Groups and Lookaheads
Advanced patterns for grouping and conditional matches.
Group patterns together
Groups multiple patterns to treat them as a single unit.
(abc)Positive lookahead assertion
Matches a group if it is followed by another pattern (but doesn't consume it).
(?=abc)Negative lookahead assertion
Matches a group if it is not followed by another pattern (but doesn't consume it).
(?!abc)Capture groups
Captures matched text for reference or replacement.
(group)Non-capturing group
Groups patterns without capturing the matched text.
(?:abc)Named capture group
Captures matched text with a name.
(?<name>group)Positive lookbehind assertion
Matches a group if it is preceded by another pattern (but doesn't consume it).
(?<=abc)Negative lookbehind assertion
Matches a group if it is not preceded by another pattern (but doesn't consume it).
(?<!abc)Escaping Special Characters
Handling characters that have special meanings in regex.
Escape special character
Matches the literal character instead of its special meaning.
\\Literal dot match
Matches the literal '.' character.
\.Literal asterisk match
Matches the literal '*' character.
*Literal plus match
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 new lines
Extract URLs from lines and place each URL on a separate line.
\s*(https?://.*)$\n$1^(?!https?://).*$""Some text https://example.comAnother line https://example.org/pagehttps://example.netConvert matching lines to list
Add a list marker to every line containing a matching pattern.
^(.*https?://.*)$- $1https://example.comhttps://example.orgRemove matching lines
Delete every complete line containing a specific pattern.
^.*TODO:.*\r?\n?""Keep this lineTODO: remove this lineKeep this tooRemove non-matching lines
Keep only lines that match a pattern and delete everything else.
^(?!.*TODO:).*(?:\r?\n|$)""Keep TODO: this itemDelete this lineKeep TODO: another itemExtract from parentheses
Replace each line with only the text contained inside parentheses.
^.*\(([^()]*)\).*$$1John Smith ([email protected])Jane Doe ([email protected])Extract between delimiters
Replace each line with the text between two known delimiters.
^.*\[(.*?)\].*$$1Name: [Kevin]Name: [Alex]Wrap values in quotes
Find values matching a pattern and surround them with quotes.
\b\d+\b"$&"123456789Add commas to multiline values
Add a comma to the end of every non-empty line for converting line-separated values into a list.
^(.+)$$1,applebananaorangeConvert to quoted list
Transform one value per line into quoted, comma-separated values.
^(.+)$"$1",applebananaorangeSwap two line values
Swap two delimiter-separated values using capture groups.
^([^,]+),\s*(.+)$$2, $1Smith, JohnDoe, JaneReformat Last First names
Convert names from "Last, First" format to "First Last".
^([^,]+),\s*(.+)$$2 $1Smith, JohnDoe, JaneIndent matching lines
Add indentation to every line matching a specific pattern.
^(import .+)$" $1"import fooconst value = 1import barRemove leading indentation
Remove all leading spaces and tabs from lines.
^[ \t]+""first line second line third lineNormalize trailing whitespace
Remove spaces and tabs from the ends of every line.
[ \t]+$""Add blank lines between matches
Insert a blank line after every line matching a pattern.
^(#+ .+)$$1\n# HeadingContent## Another headingMore contentJoin wrapped lines
Join consecutive lines that belong to the same paragraph while preserving blank lines.
(?<!\n)\n(?!\n)" "Convert HTML attributes
Replace an HTML attribute value while preserving the surrounding tag.
(<img\b[^>]*\bsrc=")[^"]*(")$1/new/path/image.jpg$2<img src="/old/path/image.jpg" alt="Example">Rename HTML attribute
Rename an attribute everywhere while preserving its value.
\bdata-old="([^"]*)"data-new="$1"<div data-old="123"><span data-old="456">Convert Markdown links to URLs
Replace Markdown links with only their destination URLs.
\[([^\]]+)\]\((https?://[^)]+)\)$2[Google](https://google.com)[YouTube](https://youtube.com)Convert Markdown links to HTML
Convert Markdown links into HTML anchor elements.
\[([^\]]+)\]\((https?://[^)]+)\)<a href="$2">$1</a>[Google](https://google.com)Remove Markdown link formatting
Keep the visible link text while removing the Markdown destination.
\[([^\]]+)\]\([^)]+\)$1[Google](https://google.com)[Example](https://example.com)Convert Markdown headings
Convert Markdown headings into HTML heading elements while preserving heading levels and text.
^#{1,6}\s+(.+)$"<h$#>$1</h$#>"Find duplicate lines
Find repeated complete lines so duplicates can be reviewed or removed.
^(.+)(?:\r?\n\1)+$applebananaappleorangeFind duplicate adjacent values
Find repeated words or values appearing consecutively.
\b(\w+)\s+\1\bvery very importantFind repeated case-insensitive words
Find consecutive duplicate words regardless of capitalization.
\b([A-Za-z]+)\s+\1\bThe the quick brown foxFind multi-pattern lines
Find lines that contain both required patterns without caring about their order.
^(?=.*foo)(?=.*bar).*$foo and bar appear on this lineFind lines missing pattern
Find complete lines that do not contain a required pattern.
^(?!.*foo).*$foo is presentthis line does not contain itFind values with surrounding whitespace
Find a value while capturing its meaningful content and excluding surrounding whitespace.
^\s*(.*?)\s*$ some valueReplace first occurrence per line
Replace the first occurrence of a pattern on each line while leaving later occurrences unchanged.
^(.*?)foo$1barfoo foo fooReplace after delimiter
Preserve the beginning of each line and replace everything after a known delimiter.
^([^:]+):.*$$1: new valuename: old valuestatus: old valueReplace before delimiter
Preserve the end of each line and replace everything before a known delimiter.
^.*:\s*(.+)$new key: $1old key: valueanother key: valueExtract file extensions
Replace filenames with only their final file extension.
^.*\.([^.]+)$$1image.pngdocument.pdfarchive.tar.gzChange file extensions
Replace the extension of every matching filename while preserving the filename.
^(.+)\.[^.]+$$1.webpimage.pngphoto.jpggraphic.gifConvert kebab-case to camelCase
Convert hyphenated words into camelCase using a capture group.
-([a-z])\u$1my-component-nameConvert snake_case to camelCase
Convert underscore-separated words into camelCase.
_([a-z])\u$1my_component_nameRemove line comments
Remove inline comments while preserving the content before the comment marker.
^(.*?)(?:\s*#.*)?$$1command --option valueExtract quoted strings
Find and capture text enclosed in single or double quotes.
(["'])(.*?)\1"hello world"'another value'Find TODO or FIXME lines
Find development notes such as TODO and FIXME regardless of capitalization.
^.*\b(?:TODO|FIXME)\b.*$// TODO: refactor this// FIXME: handle error caseFind 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.
(?:\r?\n\s*){3,}\n\nAdd newline after delimiters
Split a single-line list into separate lines after a delimiter.
,\s*\napple, banana, orangeSplit key-value pairs
Split semicolon-separated key-value pairs onto separate lines.
;\s*\nname=Kevin;role=developer;active=trueExtract URLs from text
Find HTTP and HTTPS URLs embedded anywhere in text.
https?://[^\s<>"')]+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,}\bContact [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.-]+)?\bversion 2.4.1-beta.3Find ISO dates
Find dates formatted as YYYY-MM-DD.
\b\d{4}-\d{2}-\d{2}\bPublished 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})?\bcolor: #fff; background: #1a2b3cFind CSS declarations
Capture CSS property names and values for bulk editing.
^\s*([A-Za-z-]+)\s*:\s*([^;]+);? color: #fff;Find JSON keys
Find quoted JSON property names while preserving their names for replacement.
^[ \t]*"([^"\\]+)"\s*:"name": "Kevin","email": "[email protected]",Convert JSON keys
Rename JSON keys while leaving their values untouched.
(^\s*)"oldName"(\s*:)$1"newName"$2{ "oldName": "value"}Wrap lines in tags
Wrap every complete line in a consistent opening and closing tag.
^(.+)$<item>$1</item>FirstSecondThirdPrefix matching lines
Add a prefix only to lines containing a specific pattern.
^(?=.*error)(.*)$"ERROR: $1"request succeededrequest error occurredanother errorSuffix matching lines
Add a suffix only to lines containing a specific pattern.
^(?=.*TODO)(.*)$"$1 <!-- review -->"TODO: update documentationcompleted taskCapture text before delimiter
Capture everything before the first occurrence of a delimiter.
^([^:]+):name: KevinCapture text after delimiter
Capture everything after the first occurrence of a delimiter.
:\s*(.*)$name: KevinMatch basic parentheses
Match simple parenthesized content when nested parentheses are not required.
\([^()]*\)Function (argument value)Match content between HTML tags
Capture the content inside a specific HTML element.
<p\b[^>]*>(.*?)</p><p>This is the content.</p>Remove HTML tags
Strip simple HTML tags while preserving their text content.
<[^>]+>""Convert line endings
Normalize Windows CRLF line endings to LF.
\r\n\nFind trailing punctuation lines
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.
^(.+?)[,;:]+$$1Find 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)\bwidth: 24pxmargin: 1.5remheight: 50vhFind function calls
Capture function names and their arguments for bulk code transformations.
\b([A-Za-z_$][\w$]*)\(([^()]*)\)console.log("hello")Convert function syntax
Transform simple function calls using captured function names and arguments.
\b([A-Za-z_$][\w$]*)\(([^()]*)\)$1[$2]foo(bar)baz(qux)Find package imports
Find JavaScript or TypeScript imports originating from a specific package.
^import\s+.*\s+from\s+["']some-package["'];?$import { foo } from "some-package";Find TODO comments
Find TODO comments while capturing the message for review or extraction.
\bTODO\b[:\s]*(.+)$// TODO: replace this implementationFind unmatched quotes
Find lines containing an odd number of double quotes, useful for locating malformed quoted values.
^(?:[^"]*"[^"]*")*[^"]*"[^"]*$name: "KevinMatch repeated separators
Find runs of repeated punctuation that can be normalized.
([|,_-])\1+foo---bar___bazNormalize repeated separators
Replace repeated separators with a single separator.
([|,_-])\1+$1foo---bar___bazFind delimiter surrounding whitespace
Find inconsistent whitespace surrounding commas, colons, or equals signs.
\s*([,:=])\s*name : KevinNormalize delimiter spacing
Normalize whitespace around a delimiter while preserving the delimiter.
\s*([,:=])\s*$1name : KevinExtract frontmatter fields
Capture the value of a specific YAML frontmatter field.
^title:\s*(.+)$title: My CheatsheetReplace frontmatter field
Replace the value of a specific YAML frontmatter field without changing the field name.
^(title:\s*).+$$1New Titletitle: Old TitleFind multiline blocks
Match a block beginning with one marker and ending at the next marker using a lazy match.
^START$[\s\S]*?^END$STARTcontentmore contentENDRemove multiline blocks
Delete complete blocks between explicit START and END markers.
^START$[\s\S]*?^END$\r?\n?""Find repeated delimiter content
Capture content between matching delimiter characters such as triple backticks.
```([\s\S]*?)``````code here```Extract Markdown code blocks
Capture the contents of fenced Markdown code blocks without the surrounding fences.
^```(?:\w+)?\r?\n([\s\S]*?)^```$```tsconst value = 1;```Convert code fences
Replace fenced code blocks with another delimiter while preserving their contents.
^```(?:\w+)?\r?\n([\s\S]*?)^```$<pre>$1</pre>Move captured text to new line
Capture part of each line and move it onto its own line.
^(.*?)(\s+)(https?://\S+)$$1\n$3Visit https://example.comDocumentation https://example.org/docsKeep URL matching lines
Delete every line that does not begin with an HTTP or HTTPS URL.
^(?!https?://).*(?:\r?\n|$)""https://example.comSome unrelated texthttps://example.orgExtract URLs into clean list
Extract URLs from arbitrary lines, then remove the surrounding text and preserve one URL per line.
^.*?(https?://\S+).*$$1Website: https://example.comDocs: https://example.org/docsFind pattern beginning lines
Find complete lines beginning with one of several alternatives.
^(?:ERROR|WARN|INFO)\b.*$INFO Application startedWARN Cache expiredDEBUG Request receivedFind pattern ending lines
Find complete lines ending with one of several alternatives.
^.*(?:\.js|\.ts|\.tsx)$src/index.tssrc/app.tsxREADME.mdReplace selected file extensions
Change only specified extensions while preserving the filename.
^(.+)\.(?:js|jsx|ts)$$1.mjsapp.jscomponent.jsxserver.tsREADME.mdAdd extension to extensionless files
Add a file extension to matching filenames that do not already have one.
^([^./]+)$$1.txtREADMELICENSEnotesFind active TODOs
Find TODO markers that are not immediately followed by a completed status.
^(?!.*TODO\s*DONE).*TODO.*$TODO: fix thisTODO DONE: already handledFind deprecated API usage
Find calls to a deprecated function while avoiding comments and unrelated identifiers.
\bdeprecatedFunction\s*\(deprecatedFunction(value)Find prefixed quoted values
Find quoted strings whose contents begin with a known prefix.
["'](?:https?://)[^"']+["']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}$).+$2026-08-1008/10/20262026-8-10