Knowledge to learn their own hand is their own, if the copy and paste of other people’s help is not great, it can only help themselves to solve temporary problems (sometimes also spend a lot of time to find their own), but can not fundamentally solve the problem.

Like some time ago my university classmate asked me a regular problem, how to validate user input password must contain characters, Numbers, special symbols, he said on the baidu to find a lot of regular sample can’t solve the problem, I will ask then, he said to me I ask you, I was speechless, because I was doing projects, temporarily didn’t want to come out, I told him that you didn’t try to change your mind. If you haven’t found a regular to solve this problem for the time being, you shouldn’t try to judge characters, numbers and special characters separately and then calculate and. Besides, it’s not good for user experience to give a result after using a regular judgment. Different prompts should be provided for the user to enter different situations. If the password does not contain digits, the prompt does not contain digits, and if there are no characters, the prompt does not contain…… , if you feel too much judgment by analogy, you can simplify processing, such as only password composition contains two, prompt a missing one, if the password composition contains only one, prompt password should have characters, numbers, special symbols.

This gave me a vivid lesson, not only other people ignore regular, I also ignore, lack. So while I’ve been trying to nail the design pattern high ground lately, I decided to take some time out to brush up on my regular knowledge.

A character with a special meaning

Below is a list of commonly used characters and my personal classification of them.

Grouping and set

  • (a): The expression in parentheses represents a grouping
  • []: Expressions in square brackets represent a collection

The operator

  • ^: If it appears in the set ([]), or is a locator, matching from the front edge of the string
  • |It means to operate or, to operate or
  • ? :It is placed before the first option to eliminate the side effect that correlation matches are cached

locator

  • ^: It defines the front boundary of the regular operation
  • $: It defines the back boundary of the regular operation
  • \b: Matches the boundary of a character (i.e. the boundary between characters and whitespace characters)

Character class (representing a class of characters)

  • \d: stands for numbers, while\DThe digital
  • \w: stands for words, while\WThe word
  • \s: represents whitespace, and\D, non-whitespace characters
  • .: Any character

qualifiers

It is used to specify the length or number of matches.

Matches the expression before the symbol

  • + : One or more times

  • * : zero or more times

  • ? : Zero or once

  • {} : The number of matches is related to the values in parentheses.

    If {n}, it matches n times; If {n,}, it matches at least n times; If {n,m}, it matches any number of times between n and m.

How to play regular

Re used in the string processing, can reduce our JS code to write, optimize our code, at the same time for us to learn other people’s source code complex re has helped.

Here’s a photo from Zhihu about how you learned regular expressions. A graph of the problem, and knowing the re of the graph, you can probably solve most of the problems you face.

regular

/^\s*[A-Za-z_$][\w$]*(? :\.[A-Za-z_$][\w$]*|\['*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*\s*$/Copy the code

Here are some examples of visual regular editors.

Regexper (one of the first I encountered)

Regulex (this is the one I use a lot now)

RegExr (this is very powerful and is very helpful for learning regular, and is highly recommended if you are learning regular)

How to use JS

Re is a powerful way to query and replace strings.

Before we always wonder sometimes converts a string to a numeric array, the method of using the array to process the character, but want to know the string is common in our life and work, in the form of Numbers, array, the Boolean type is relatively small, especially when doing WeChat development recently found it important to regular, examples of my classmate, It only gives me a motivation for further study and research. This is just my preliminary summary, which will be further strengthened if necessary.

In JavaScript we use RegExp to create an object to implement a regular expression.

The basic definition

A re has two parts: the re body and the modifier.

The form is as follows:

regExp = new RegExp('pattern', 'flag'); // regExp = /pattern/gmiCopy the code

There are five types of regular modifiers, which are:

  • g: all matches, if not, only one match
  • i: Ignores the case of characters
  • m: Supports multiple lines
  • u: support Unicode
  • y: Strict mode (returns a match at the specified location)

Some methods of re objects

regexp.test(str)

The test method returns true/false

let str = "Hello world!" ; let regexp = /hello/i; console.log(regexp.test(str));Copy the code
regexp.exec(str)

Because this method is not easy to use, few people use it.

let str = "Hello world!" ; let regexp = /l(o)/ig; // If matchOne = regexp. Exec (STR); if matchOne = regexp. console.log(matchOne[0]); // lo console.log(matchOne[1]); // o console.log(matchOne.index); // 3 console.log(matchOne.input); // Hello world! console.log(matchOne.lastIndex); / / 5Copy the code

Returns NULL if there is no match

Js String can use the regular method

Using re in the String method can easily solve our daily development problems.

str.search()

Returns the first character position of the first matching result, if any; Otherwise, return '-1'. let str = "Hello world!" ; regexp = /o/i; str.search(regexp); / / 4Copy the code

Note; Search can only return the results of the first match, not other matches

str.match(str|reg)

let str = "Hello world!" ; regexp = /o/i; let result = str.match(regexp); console.log(result[0]); // o console.log(result.index); // 4 console.log(result.input); // Hello world!Copy the code

We find that the use of str.match() is exactly the same as the result returned by regexp.exec(). The underlying implementation of match is regexp.exec(), as well as the use of the g modifier.

str.split(reg|substr, limit)

Splits the given string word by word, returning an array of words.

let str = 'Hello world, my   name  is lzb.'
let regexp = /\s+/i;
str.split(regexp); // ["Hello", "world,", "my", "name", "is", "lzb."]
str.split(regexp, 3) //  ["Hello", "world,", "my"]
Copy the code

The second argument in the string method limits the length of the returned result array.

In the result returned, we find some words with special symbols. The following string method will remove the special symbols.

str.replace(str|reg, str|func)

To achieve the goal of removing special characters from the above example, we could use str.replace(), which looks like this:

let str = 'Hello world, my name is lzb.' let regexp = /[.,\/#!$%\^&\*;:{}=\-_`~()]/g; str.replace(regexp, ''); / / "Hello world my name is LZB" or let STR = 'Hello world, my name is LZB.' let the regexp = / | -] [^ \ w \ s/g; str.replace(regexp, ''); // "Hello world my name is lzb"Copy the code

Then, follow up with the str.split() method above, or some of you might think of something like this:

let str = 'Hello world, my   name  is u-lzb.'
let regexp = /[^\w]+/g;
str.split(regexp); // ["Hello", "world", "my", "name", "is", "u", "lzb", ""]
Copy the code

This method is not recommended, but the problem is obvious and won’t be covered here.

We find that there are two ways to clear a particular character in a string, and neither is superior to the other. If we put the string work_UP, call&apply, ::arg, a=b… As special words, we need the first method; If we’re just trying to keep things in order we can use the second method.

If the second argument is func, here is an example of capitalizing the first letter of a word in a string:

let str = 'hello world'; Str.replace (/\b\w+\b/g, (word) => word.substring(0,1).touppercase () + word.substring(1));Copy the code

String methods include Length, indexOf, concat, toLowerCase, toUpperCase, etc., which are not covered here.

recommended

If you like code topic’s classmate to www.hackerrank.com/domains/reg… This website goes.

Github.com/lvzhenbang/…