What is a quantifier? How to understand quantifiers?

Quantifiers are used to set the number of occurrences of a certain pattern. By using quantifiers (?, +, *,) the matching of a character that appears consecutively can be completed. The details are shown in the table.
insert image description here

In the above table, "..." means multiple times. In order to better understand the use of quantifiers, let's take the a character as an example to demonstrate, and the sample code is as follows.

var reg = /~a*$/;      // * 相当于>=0,可以出现1次或很多次
var reg = /^a+$/;      //+相当于>=1,可以出现1次或很多次
var reg = /^a?$/;      //?相当于1110,可以出现0次或1次
var reg = /<a{
    
    3,}$/;   //{
    
    3} 就是重复a字符3次
var reg = /^a{
    
    3}$/;  //{
    
    3,}就是重复a字符 大于等于3次
var reg = /^a{
    
    3}$/;  //{
    
    3,16}就是重复a字符 大于等于3次 小于等于16次

In the above code, the number of occurrences of character a is used as an example to use quantifiers, but in actual development, quantifiers are usually used to indicate the number of occurrences of a certain pattern. For example, the regular expression for validating the user name learned earlier is as follows.

var reg= /^[a-zA-Z0-9 -]s/;

This mode can only allow users to input uppercase and lowercase letters, numbers, underscores, and dashes. Because there is a boundary character "n", you can only choose one more. If the user is allowed to input 6 to 16 characters, at this time, the quantifier can be used to make any one of the 6 to 16 characters in the reg pattern appear correct, which requires a customized range. The sample code is as follows.

var reg=/~[a-zA-20-9-]16,16)S/;

As can be seen from the above code, the "n" part represents the regular pattern of the user name, and the "n" part sets the number of occurrences of the pattern. Note that there can be no spaces between (6,16). Flexible use of qualifiers can make regular expressions clearer and easier to understand.

Guess you like

Origin blog.csdn.net/cz_00001/article/details/131291700