Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 3, 2020 06:38 am GMT

Regular Expressions cheat sheet

Regular expression is a powerful tool, and it can save lots of lines codes sometimes.

What is Regex

Regex(Regular Expression) describes a pattern of a certain amount of text, so it can be used for string editing.

Online tool

Not sure if your Regex works? Try Regex101, it can make your Regexes much easier.
I also recommend Regular Expression Info, it explains all details that you need to know.

Cheat Sheet

CharacterMeaningExample
^the beginning of the string
$the end of the string
\bwhole word only\babc\b matches 'abc', but not 'abcc '
\Bif the pattern is fully surrounded by word\Babc\B mathes 'aabcc', but not 'abc'
.anything
\dsingle digit in 0-9
\Dsingle non-digit
\wsingle word character
\Wsingle non-word
\swhite space(space, tab, return, new line)
\Snon-whitespace
tab
\rreturn

new line
\gglobal search, which means it doesn't stop at the first match
*zero or more of the previousabc* matches a string that has ab followed by zero or more c
+one or more of the previousabc+ matches a string that has ab followed by one or more c
?zero or one of the previousabc? matches a string that has ab followed by zero or one c
?:non-capturing group
X{m}number of X === m
X{m,}m < number of X
X{m, n}m < number of X < n
(X | Y)X or Y
[...]any of characters in the class[abcd] matches a string that has one of the char (a, b, c, d)
-range[a-d] same as above

Key words from the cheat sheet

Anchor
Anchor is not a pattern, it is a position.
It matches a position before, after or between characters.
For example, ^ is the beginning of the string, and it is also a start of line anchor.

Boundaries
\b is a word boundary because \babc\b has to match the whole word abc.
\B is non-word-boundary because \Babc\B means any words that includes abc (abcc, eabc).

Quantifiers
Greedy: The optional item is included in the match if possible. ? is a typical example of greedy quantifiers. abc? can match either abc or ab.
Lazy: * The optional item is excluded in the match if possible. ?? is a typical one because abc?? only matches ab.
Here is the best example from stack overflow - https://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions

Non-capturing group
?: means the pattern doesn't capture to the group. It usually uses with .match(). So if you use ?:, then the pattern won't be included to the array.
Example from stack overflow -
https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-in-regular-expressions

Hope this post helps


Original Link: https://dev.to/mingyena/regular-expressions-cheat-sheet-4ec3

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To