Skip to content

Instantly share code, notes, and snippets.

@omundy
Last active March 16, 2021 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omundy/0edffc81af41f514d778e555b9bab954 to your computer and use it in GitHub Desktop.
Save omundy/0edffc81af41f514d778e555b9bab954 to your computer and use it in GitHub Desktop.
Examples of often used regular expressions

Regular Expressions (REGEX)

Sites that let you test expressions

Basics

Regular expressions attempt to match characters in a string using specific symbols. Some examples:

Expression Matches Does not match Description
a a 1 Match a single a character
. a,1,[...] \n Match any single character (a-z,0-9) (except line breaks)
.+ a,1a,[...] \n Match one or more of any character (except line breaks)
[a-z] a,b,[...] 1a,1,2,[...] Match any lower case single letter
[a-z]+ a,ab,[...] 1a,1,2,[...] Match any lower case single letter one or more
([a-z]+) a,ab,[...] 1a,1,2,[...] Match any lower case single letter and place in capture group
([0-9a-fA-F]{6}) f0f0f0,[...] other,words,[...] Match hexadecimal color values
([0-9]{1,3}) 123,456,[...] 1234,words,[...] Match integers of a specific length

Examples

All of these should work in languages like Javascript and C# as well as the Find/Replace function of code editors like Atom or Visual Studio.

Find and Replace - JSON keys Live example

Find and replace a string using the matching string in the replacement. The following example adds double quotes to JSON keys by wrapping the pattern with parentheses to create a "capture group" ([a-z0-9]+(?=:)) and thus allow access to the matched string in the replacement using $1:

Example string

{
key1:"value1",
key2:"value2"
}

Pattern

([a-z0-9]+(?=:))

Replacement

"$1"

Result

{
"key1":"value1",
"key2":"value2"
}

so example How to use a regex in Atom

Find and Replace - Transform CSV to a C# dictionary Live example

Example string

52, Business, 0E6897
483, Sports, 253785
239, Hobbies, 5b11db

Pattern matches integer, string, hex value using capture groups

([0-9]{1,3})(, )([A-Za-z]+)(, )([0-9a-fA-F]{6})

Replacement with captured strings

{ $1, new MarketingColor{ category = "$3", colorStr = "$5" } },

To make C# dictionary

{ 52, new MarketingColor{  category = "Business", colorStr = "0E6897"} },
{ 483, new MarketingColor{  category = "Sports", colorStr = "253785"} },
{ 239, new MarketingColor{  category = "Hobbies", colorStr = "5b11db"} },

Find and Replace - Get stock symbols from a list

Example string

ACBI|Atlantic Capital Bancshares, Inc. - Common Stock|Q|N|N|100|N|N
ACCD|Accolade, Inc. - common stock|Q|N|N|100|N|N
ACER|Acer Therapeutics Inc. - Common Stock|S|N|N|100|N|N

Pattern

(^[A-Z]{1,5})+(.*)

Replacement

$1

Result

ACBI
ACCD
ACER
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment