1. Syntax
There are two ways to define a regular expression
var expression = /pattern/flags
Explanation of the quoted MDN:
pattern: The text of the regular expression.
Flags: Flags, which can be any combination of the following values:
- G: global match; Find all matches, not stop after first match
- I: Ignore case
- M: Multiple lines; The start and end characters (^ and $) are considered to work on multiple lines (that is, match the start and end of each line separately (by \ n or \ r), not just the beginning and end of the entire input string.
- U:unicode; To treat a pattern as a sequence of Unicode sequence points (ES6 new)
- Y: viscous matching; Matches only the index indicated by the Lastindex property of this regular expression in the target string (and does not attempt to match from any subsequent index). (ES6 added.) This is not good to understand can look at two chestnuts regexp.prototype.sticky[mdn],what does regex ' flag ' y ' do?
eg
var pattern = /at/gi;
var expression = new RegExp(pattern, flags);
eg
var pattern2 = new RegExp("at", "gi");
These two types of writing actually have the same effect, creating a new RegExp
instance .
RegExp
Each instance has the following properties:
flags
: All flags. (ES6 New)
global
: Boolean that indicates whether the G flag is set.
ignoreCase
: Boolean that indicates whether the I flag is set.
multiline
: Boolean that indicates whether the M flag is set.
lastIndex
: Indicates where to start searching for the next occurrence, starting from 0. (Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex)
source
: A string of pattern text for the current regular expression object that does not contain a slash along the sides of the regular literal and any flag characters.
2. How to use
Simple string matching can be used in a String.match()
method.
eg
var str = "cat, bat, sat, fat";var pattern = /.at/g;str.match(pattern);
Output:
If you only need to know if there is a match and don't care about the content, you can use the RegExp.test()
method. The method returns a Boolean value that indicates whether the match succeeded.
eg
var str = "cat, bat, sat, fat";var pattern = /.at/g;pattern.test(str);
Output:
If you need to use a capture group, use the RegExp.exec()
method. The method returns the matching result, which is returned if no match is successful null
.
eg
var pattern = /aaa and (bbb and (ccc))/g;var text = "this is aaa and bbb and ccc";pattern.exec(text);
Output Result:
Where the first item in the array is a string that matches the entire pattern, the other item is a string that matches the capturing group in the pattern. If no capturing group is in the pattern, the array contains only one item.
Use of JavaScript regular expressions