Regular Expression in JS

In javascript, regex use the delimiter /.

  • The syntax is like this: /<pattern>/<modifier>

Modifiers

Modifiers

  • g - Perform a global match (find all matches rather than stopping after the first match)
  • i - Perform case-insensitive matching
  • m - Perform multiline matching

Pattern - Anchors

  • ^ - means pattern in the beginning of words
  • $ - means pattern in the last of words

Pattern - Brackets

In brackets, ^ means NOT, instead of the beginning of the line.

  • [abc] - Find any character between the brackets
  • [^abc] - Find any character NOT between the brackets
  • [0-9] - Find any character between the brackets (any digit)
  • [^0-9] - Find any character NOT between the brackets (any non-digit)
  • (x|y) - Find any of the alternatives specified; () defines a group

Pattern - Metacharacters

Metacharacters are characters with a special meaning

  • . - Find a single character, except newline or line terminator
  • \w - Find a word character, including a-z, A-Z, 0-9, and _
  • \W - Find a non-word character
  • \d - Find a digit
  • \D - Find a non-digit character
  • \s - Find a whitespace character, including a space / tab / new line character
  • \S - Find a non-whitespace character
  • \b - Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b
  • \B - Find a match, but not at the beginning/end of a word
  • \n - Find a new line character
  • \t - Find a tab character

Pattern - Quantifiers

  • n+ - Matches any string that contains at least one n
  • n* - Matches any string that contains zero or more occurrences of n
  • n? - Matches any string that contains zero or one occurrences of n
  • n{X} - Matches any string that contains a sequence of X n’s
  • n{X,Y} - Matches any string that contains a sequence of X to Y n’s
  • n{X,} - Matches any string that contains a sequence of at least X n’s
  • ?=n - Matches any string that is followed by a specific string n
  • ?!n - Matches any string that is not followed by a specific string n

Some Common Patterns

Match a positive integer

  • ^\d+$
    • postive integer starting will 0 is excluded (e.g. 012)
  • ^[1-9]\d*$
  • ^[1-9][0-9]*$

Match a negative integer

  • ^-[1-9]\d*$
  • ^-[1-9][0-9]*$

Match an integer

  • ^-?[1-9]\d*$
    • 0 is excluded
  • ^-?[1-9][0-9]*$
    • 0 is excluded
  • ^(0|-?[1-9][0-9]*)$
  • ^(0|-?[1-9]\d*)$

Match a decimal number, e.g., 3.5

  • ^-?(0|[1-9]\d*)\.\d+$

Match a integer or decimal number

  • ^[0-9]\d*(\.\d+)?$
    • positive numbers only
  • ^-?[0-9]\d*(\.\d+)?$
    • cover both postives or negatives

Match an email

  • ([\w\.-]+)@([\w\.-]+)(\.[\w\.]+)

Match a Date (dd mm yyyy, d/m/yyyy, etc.):

1
^([1-9]|0[1-9]|[12][0-9]|3[01])\D([1-9]|0[1-9]|1[012])\D(19[0-9][0-9]|20[0-9][0-9])$

Match Year 1900 - 2099

1
^(19|20)[\d]{2,2}$

More Examples:

https://digitalfortress.tech/tricks/top-15-commonly-used-regex/

Using Regex in JS

Search and Replace

  • search() uses a regular expression to search for a match and returns the position of the match.
  • replace() returns a modified string where the pattern is replaced.

Example:

1
2
3
4
5
6
var str = "Vines Note :)";
var n = str.search("Note");
console.log(n); // 6

var res = str.replace(/note/i, "Book")
console.log(res); // Vines Book :)

Test and Exec

  • test() searches a string for a pattern, and returns boolean value whether it exists or not.
  • exec() searches a string for a specified pattern and returns the found text as an object.

Example:

1
2
3
4
5
6
7
8
9
var pattern = /e/g; 
var str = "The best things in life are free!";
console.log(pattern.test(str));
console.log(/e/g.test(str));

/*
true
true
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
var str = "is this his shirt"; 
var pat = /is/g;
var result;
while ((result = pat.exec(str)) != null) {
console.log(result+" "+ pat.lastIndex);
}

/*
is 2
is 7
is 11
*/

Regular Expression in PHP

In PHP, regex also use the same delimiter /.

  • The syntax is like this: /<pattern>/<modifier>

For the regex rules, same as JS.

Using Regex in PHP

PHP provides a variety of functions that allow you to use regular expressions.

  • preg_match($pattern, $str) - tell you whether a string contains matches of a pattern (1 or 0)
  • preg_match($pattern, $str) - tell you how many matches of a pattern
  • preg_replace($pattern, "<replacement>", $str) - replace all of the matches of the pattern with another string
  • preg_split($pattern, $str) - breaks a string into an array using matches of a regular expression as separators.

Examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";

echo preg_match($pattern, $str);

// Outputs 1

echo preg_match_all($pattern, $str);

// Outputs 4

echo preg_replace($pattern, "??", $str);

// Outputs "The r? in SP? falls m?ly on the pl?s."
?>
1
2
3
4
5
6
7
8
<?php
$date = "2020-10-15 16:30:00";
$pattern = "/[-\s:]/";
$components = preg_split($pattern, $date);
for($i=0; $i<count($components); $i++)
echo "$components[$i] ,";
//Output "2020 10 15 16 30 00"
?>