Regex Cheatsheet
We can use regular expression for regular find operations as well as replace.
Symbol | Description | Sample Text | Regex | Output | |
---|---|---|---|---|---|
Letters | \w | Matches any latin letter or digit | Sample | \w | S a m p l e |
\W | Matches any non-alphanumeric character | ||||
Digits | \d | Matches any decimal digit | Numbers: 1, 2, 3, 100, 200 | \d | Numbers: 1 , 2 , 3 , 1 0 0 , 2 0 0 |
\D | Matches any non decimal digit character. | ||||
Repetition | + | Matches one or more repetition of symbol (select whole word or digit) | Sample Text. | \w+ | Sample Text . |
Repetition | * | Matches Zero or more occurrences of the symbol | 1 , 2, 3, 10, 20, 100, 200 | \d\d* | 1 , 2 , 3 , 10 , 20 , 100 , 200 |
Set | [] | Matches set of characters | All symbols inside the braces. | [abc] will match a,b or c | A ll symb ols inside the b rac es. |
[a-c] | Works similarly to [abc] | ||||
[^abc] | Match any character except a,b or c | [^abc] | All sym bols inside the br aces . | ||
Special Symbols | \. \[ \+ | Match symbols that bear special meaning for regex. need to escape with \ | 2+2 | + | 2+ 2 |
Alteration | a|b | Will match a or b | numbers: 1, 2, 3, 100 | [a-f]|\d | numb ers: 1 , 2 , 3 , 1 0 0 |
Single Character | . | Matches any character other than newline | This is test. | .* | This is test. |
Optional | ? | Makes the symbol optional | he and she | s?he | he and she |
Start Of string | ^ | Matches the start of a string without consuming characters | start of string | ^\w+ | start of string |
End Of string | $ | Matches the end of string without consuming characters | end of string | \w+$ | end of string |
Word Boundary | \b | Matches boundaries of word. \b\w and \w\b will match first and last letter in word. | Immortal Gods | \b\w | I mmortal G ods |
Immortal Gods | \w\b | Immortal Gods | |||
Space Symbol | \s | Match any space symbols | This is test. | \s | This is test. |
\S | Matches a single character which is not white space. | ||||
Number of Repetitions | {min_num, max_num} | Number of repetitions for an expression. | I remember, Nick. | \w{3,5} | I remem -ber , Nick |
{n} | Exactly n receptions | I remember, Nick. | \w{3} | I rem -mem ber, Nic k. | |
{n,} | N or more | I remember, Nick. | \w{3,} | I remember , Nick . | |
Grouping | () | Group of the match by putting them in braces. | John Smith | (\w+)\s(\w+) | John Smith |
Replacing | $1 $2 | We can use groups for replacing, referencing by numbers: $1 $2 (selecting group 1 and group 2 using $1 $2) | John Smith | (\w+)\s(\w+) replace with $2 $1 | Smith John |
Backreferenace (Contents In Capture Group) | \1 | It will return a string with the content from the first capture group. 1 can be any number as long as it corresponds to a valid capture group. | 6362888232275296622 | (\d)\1 | 636288 82322 752966 22 |
Lookeaheads | (?=) | abc(?=d) will match abc only if it is followed by d. | abcd | abc(?=d) | abc d |