Patterns and Flags

Patterns and Flags (图案和标志)

Regular expressions are the patterns, providing a robust means of searching and replacing in the text. (正则表达式是模式,提供了一种在文本中进行搜索和替换的强大手段。)

They are available via the Regexp object in JavaScript. Also, they are integrated into the methods of strings. (它们可通过JavaScript中的Regexp对象获得。此外,它们被集成到字符串的方法中。)

Regular Expressions

Regular Expressions (正则表达式)

A regular expression ( or a “regexp”, “regex”, “reg”) encompasses a pattern and optional flags. (正则表达式(或“regexp”、“regex”、“reg” )包含模式和可选标志。)

Two syntaxes (long and short) are used for creating a regular expression object. (两个语法(长语法和短语法)用于创建正则表达式对象。)

The long syntax is the following:

regexp = new RegExp("pattern", "flags");

The short one uses slashes “/”, like this:

regexp = /pattern/; // no flags
regexp = /pattern/gmi; // with flags g,m and i

The slashes /…/ signal JavaScript that a regular expression is being created. The slashes here play the same role, as quotes in strings. (斜杠/…/表示正在创建正则表达式的JavaScript。这里的斜杠与字符串中的引号起着相同的作用。)

In both of the cases, regexp becomes the built-in RegExp class instance. The difference between the two syntaxes above is that pattern applying slashes, never allows the expressions to be inserted. They are static. (在这两种情况下,正则表达式都成为内置的RegExp类实例。 上述两种语法之间的区别在于,模式应用斜杠,绝不允许插入表达式。它们是静态的。)

Slashes are applied in case one knows the regular expression at the code writing time. This happens frequently. The new RegExp is used often when it is necessary to generate a regexp “on the fly” from a dynamically created string. (如果在代码编写时知道正则表达式,则应用斜杠。这种情况经常发生。当需要从动态创建的字符串“即时”生成正则表达式时,经常使用新的RegExp。)

Here is an example:

let tag = prompt("What tag do you want create?", "div");
let regexp = new RegExp(`<${tag}>`); // same as /<div>/ in case answered "div" in the prompt above

Flags

Flags

Regular expressions might also include flags, affecting the search. (正则表达式也可能包含标志,从而影响搜索。)

Only six flags exist in JavaScript:

  • i: this flag makes the search case-insensitive. There is no difference between B and b.

  • g: with this one, the search investigates all the matches without it. And only the first match is returned.

  • m: this is the multiline mode.

  • s: this flag allows a dot (.) for matching newline character \n.

  • u: with this one, you can enable full Unicode support. It activates the correct processing of surrogate pairs.

  • y: it is the “sticky” mode, allowing you to search the exact position in the text.

As for the color theme, it will be as follows:

Red for regexp. (红色表示正则表达式。)

Blue for the string. (字符串为蓝色。)

Green for the result. (结果为绿色。)

Searching: str.match

Searching: str.match

Regular expressions may also be integrated with string methods. (正则表达式也可以与字符串方法集成。)

The str.match(regexp) method uncovers the matches of regexp inside the string str . (Str.match (regexp)方法在字符串str中揭示正则表达式的匹配项。)

Three working modes are actual for it:

let str = "Welcome to w3cdoc"; 
console.log(str.match(/welcome/gi)); // Welcome (an array of two matching substrings)

In case you want the result to always be an array, then you should write it like this:

let matches = "JavaScript".match(/CSS/) || [];
if (!matches.length) {
 console.log("No matches"); // now it works
}

Replacing: str.replace

Replacing: str.replace

The str.replace(regexp, replacement) method is targeted at replacing the matches found using regexp in string str along with the replacement . (Str.replace (regexp, replacement)方法旨在替换在字符串str中使用正则表达式找到的匹配项以及替换项。)

Here is an example of using str.replace(regexp, replacement):

// no flag g
console.log("It's a HTML book, it's a html book".replace(/html/i, "Javascript"));
// with flag g
console.log("It's a HTML book, it's a html book".replace(/html/ig, "Javascript"));

The replacement is the second argument. Special character combinations can be used for inserting fragments of the match in it, like this:

SymbolsThe Action within the replacement string
$&inserting the total match
$inserting a part of the string before matching
$'inserting a string part after the match
$nin case n is a 1-2 digit number, then it will insert the contents of n-th parentheses.
$<name>inserting the contents of the parentheses with the specific name.
$$inserting the character $

An example with the usage of $& will look like this:

console.log("Welcome to w3cdoc".replace(/w3cdoc/, "$& and Javascript book")); // Welcome to w3cdoc and JavaScript book

Testing: regexp.test

Testing: regexp.test

The regexp.test(str) method searches for at least a single match. In case of finding it, true is returned, in case of not founding - false . (Regexp.test (str)方法搜索至少一个匹配项。如果找到它,则在未创建的情况下返回true - false。)

Here is an example of using the regexp.test(str) method:

let str = "Welcome to w3cdoc";
let regexp = /TO/i;
console.log(regexp.test(str)); // true

Summary

Summary (概要)

Regular expressions are a super-handy way of describing patterns in the string data. They can be used for checking a string for characters ( for instance, to look for an email address) by matching the pattern, described in the regular expression. (正则表达式是描述字符串数据中模式的超级方便的方式。它们可用于通过匹配正则表达式中描述的模式来检查字符串中的字符(例如,查找电子邮件地址)。)

So, a regular expression encompasses patterns and flags. Flags are optional. Among them are g, i, m, u, s, y. (因此,正则表达式包含模式和标志。标志是可选的。其中包括g、i、m、u、s、y。)

The search by the regexp without flags and special symbols is similar to a substring search. (没有标志和特殊符号的正则表达式搜索类似于子字符串搜索。)

The str.match(regexp) method is used to search for matches. The str.replace(regexp, replacement) method replaces the found matches using regexp with replacement. Finally, the regexp.test(str) method returns true after finding at least one match, otherwise- false. (Str.match (regexp)方法用于搜索匹配项。str.replace (regexp, replacement)方法将使用正则表达式找到的匹配项替换为替换。最后, regexp.test (str)方法在找到至少一个匹配项后返回true ,否则返回false。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部