web front-end articles: JavaScript regular expressions

JavaScript regular expressions

1. Create a regular expression

1.1 Method 1: Direct amount grammar

  • Syntax: var reg = / pattern / attributes
  • Explanation: The parameter pattern is a string that specifies a regular expression pattern or other regular expressions. Attributes is an optional parameter string containing the attribute "g", "i" and "m", are used to specify the global matching, case-insensitive match and multiple match lines.

1.2 Method 2: Create a RegExp object syntax

  • Syntax: var reg = new RegExp (pattern, attributes)
  • Explanation: The parameter pattern is a string that specifies a regular expression pattern or other regular expressions. Attributes is an optional parameter string containing the attribute "g", "i" and "m", are used to specify the global matching, case-insensitive match and multiple match lines.

1.3 difference:

1. The amount of direct regular expression syntax of the object is generated in the new code is compiled, it is commonly used in the usual manner to develop;

2. Using Regular generated constructor object to generate run time code.

1.4 regular expressions

1. regularization method object refers used:. RegExp object methods (String)

The method is to use a string object: String method (the RegExp object)

2. Regular properties of the object

2.1 Property

ignoreCase 返回布尔值,表示RegExp 对象是否具有标志 i
global 返回布尔值,表示RegExp对象是否具有标志g
multiline 返回布尔值,表示RegExp 对象是否具有标志 m。
lastIndex 一个整数,标识开始下一次匹配的字符位置
source 返回正则表达式的源文本(不包括反斜杠)
i 执行对大小写不敏感的匹配
g 执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。
m 执行多行匹配
正则表达式作用

2.2 Application

2.2.1 verification

  • When used for authentication, it is usually required before and after adding ^ and $ to match the entire string to be verified;

2.2.2 search and replace

  • Search / plus whether this replacement is defined when the search request may be, in addition, it is also possible to add \ b ^ and $ instead of before and after

2.3. Match Type

2.3.1 character match

Regular Expressions use
[…] Find any character between the brackets
[^…] Find any character not between the brackets
[a-z] Find any character from lowercase a to lowercase z,
[A-Z] Find any character from uppercase A to Z of capital
[A-z] Find any character from uppercase A to lowercase z,
. Find a single character, except for line breaks and line endings
\w Find a word character, equivalent to [a-zA-Z0-9]
\W Find a non-word character, equivalent to[^a-zA-Z0-9]
\s Find a blank character
\S Find a non-whitespace characters
\d Find figures, equivalent to [0-9]
\D Finding non-numeric characters, equivalent to[^0-9]
\b Match a word boundary
\r Find carriage return
\t Find Tabs
\0 Find NULL character
\n Find newline

2.3.2 repeated characters match

Regular Expressions use
{n,m} Before a match at least n times, but not more than m times
{n,} Match the preceding n or more times
{n} N times before a match
n? Match preceding zero or 1, that is to say a front is optional, it is equivalent to {0,1}
n+ Before a matching one or more times, equivalent to {1}
n* Before a match zero or more times, equivalent to {0}
n$ Matches any string of n ends of
^n Matches any string of the beginning of the n
?=n Immediately followed by the specified string matches any character string n
?!n Immediately thereafter not match any character string specified string n

2.3.3 match specific digital

Regular Expressions use
^[1-9]\d*$ Matching a positive integer
^-[1-9]\d*$ Matching negative integer
^-?[0-9]\d*$ Matching integer
^[1-9]\d*|0$ 0 $ matching non-negative integer (integer + 0)
^-[1-9]\d*|0$ Non-matching positive integer (0 + negative integer)
^[1-9]\d*.\d*|0.\d*[1-9]\d*$ Matching positive float
^-([1-9]\d*.\d*|0.\d*[1-9]\d*)$ Matching negative float
^-?([1-9]\d*.\d*|0.\d*[1-9]\d*|0?.0+|0)$ Match float
^[1-9]\d*.\d*|0.\d*[1-9]\d*|0?.0+|0$ Matching non-negative floating point number (floating-point number n + 0)
^(-([1-9]\d*.\d*|0.\d*[1-9]\d*))|0?.0+|0$ Non-matching positive float (negative float + 0)

2.3.4 match a particular string

Regular Expressions use
^ [A-Za-z] + $ Matching string of 26 English letters
^[A-Z]+$ Matching string of uppercase letters 26 composed of
^[a-z]+$ A matching string 26 composed of lowercase letters
^ [A-Za-z0-9] + $ Matching string of numbers and English letters 26
^\w+$ Matching string of digits, letters or underscore 26 composed of

3 method

3.1 test method

Value specified in the search character string. Returns true or false. Value specified in the search character string. Returns true or false.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>text</title>
</head>
<body>
    <script type="text/javascript">
        var reg = /123/g;
        var str = 'hello123hello123';
        console.log(reg.test(str));//true
        console.log(reg.lastIndex);//8
        console.log(reg.test(str));//true
        console.log(reg.lastIndex);//16
        console.log(reg.test(str));//false
        console.log(reg.lastIndex);//0
        
    </script>
</body>
</html>
//使用了g修饰符的正则表达式,表示要记录每一次搜索的位置,接着使用test方法,每次开始搜索的位置都是上一次匹配的后一个位置。

3.2 exec method

A method for matching a regular expression string retrieved. It returns an array in which to store the matching results. If a match is not found, the return value is null.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>exec</title>
</head>
<body>
    <script type="text/javascript">
        var str='abc';
        var reg1 = /x/;
        var reg2 = /a/;
        console.log(reg1.exec(str));//null
        console.log(reg2.exec(str));//array["a", index: 0, input: "xyz"]

    </script>
</body>
</html>

If the regular expression contains parentheses, the returned array will include multiple elements. First, the entire result of a successful match, followed by parentheses matching successful result, if there are multiple parentheses, the result of their match will be the success of the array elements

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>exec</title>
</head>
<body>
    <script type="text/javascript">
        var str='abcdabc';
        var reg1 = /(a)b(c)/;
        console.log(reg1.exec(str));//["abc", "a", "c", index: 0, input: "abcdabc", groups: undefined]
    </script>
</body>
</html>

3.3 search method

search () method for substring search character string specified, retrieving or regular expression matching substring.

Return Value: stringObject regexp with the first substring that matches the starting position.

Note: If no matches any substring, or -1.

​ search() 方法不执行全局匹配,它将忽略标志 g。它同时忽略 regexp 的 lastIndex 属性,并且总是从字符串的开始进行检索,这意味着它总是返回 stringObject 的第一个匹配的位置。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>search</title>
</head>
<body>
    <script type="text/javascript">
        var str='abcdefgh';
        console.log(str.search('h'))//7
    </script>
</body>
</html>

3.4match方法

​ match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。

​ 字符串对象的match方法与正则对象的exec方法比较类似:但是如果正则表达式带有g修饰符,那么match方法与exec方法就有差别了:可以看到match返回了所有成功匹配的结果,但是exec方法只返回了一个。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>match</title>
</head>
<body>
    <script type="text/javascript">
        var str = "abcd";
        var reg1 = /a/;
        var reg2 = /x/;
        console.log(str.match(reg1));//a
        console.log(str.match(reg2));//null

        var str2 = "abcabc";
        var reg3 = /a/g;
        console.log(str2.match(reg3));//['a','a']
    </script>
</body>
</html>

3.5 replace方法

​ replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

返回值:一个新的字符串,是用 replacement 替换了 regexp 的第一次匹配或所有匹配之后得到的。

​ 字符串 stringObject 的 replace() 方法执行的是查找并替换的操作。它将在 stringObject 中查找与 regexp 相匹配的子字符串,然后用 replacement 来替换这些子串。如果 regexp 具有全局标志 g,那么 replace() 方法将替换所有匹配的子串。否则,它只替换第一个匹配子串。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>replace</title>
</head>
<body>
    <script type="text/javascript">
        var str = "aaa";
        console.log(str.replace('a', 'f'));//fbcdaa
    </script>
</body>
</html>

3.6 split方法

​ split(‘字符串的分割正则','返回数组的最大成员数');返回分割后各部分组成的数组

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>split</title>
</head>
<body>
    <script type="text/javascript">
        var str = "a,b,c,d,e,f";
        var res = str.split(",");//以逗号来分割字符串
        console.log(res);//["a", "b", "c", "d", "e", "f"]
        var str2 =  "a, b ,c,d";
        var res2 = str2.split(/, */);//以0或对个逗号空格来分割字符串
        console.log(res2);//["a", "b ", "c", "d"]
    </script>
</body>
</html>

3.7示例:

  • 从URL中提取子域名
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>split</title>
</head>
<body>
    <script type="text/javascript">
          var url = "http://www.abc.com";
          var reg = /[^.]+/;//匹配除了.之外的其他字符
          var res = reg.exec(url)[0].substr(7);
          console.log(reg.exec(url));//["http://www", index: 0, input: "http://www.abc.com"]
          console.log(res);//www
    </script>
</body>
</html>

4.常用正则匹配

匹配国内电话号码:\d{3}-\d{8}|\d{4}-\d{7}

如 0511-4405222 或 021-87888822

匹配QQ号:[1-9][0-9]{4,}

从10000开始

邮政编码:[1-9]\d{5}(?!\d)

邮政编码为6位数字

匹配身份证:/^(\d{14}|\d{17})(\d|[xX])$/

匹配规则:身份证号码有15位或者18位,其中最后一位可能是X,其他全是数字

匹配ip地址:\d+.\d+.\d+.\d+

匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$ 表单验证时很实用

匹配中文字符: /[\u4E00-\u9FA5\uf900-\ufa2d]/

使用 Unicode,必须使用\u开头,接着是字符编码的四位16进制表现形式

匹配Email地址:

/^([a-zA-Z_0-9-])+@([a-zA-Z_0-9-])+(.[a-zA-Z_0-9-])+$/

邮箱的规则是: 由3部分组成

由1个或者多个字母数字下划线和杠 + @ + 1个或者多个字母数字下划线和杠 + . + 1个或者多个字母数字下划线和杠

匹配网址URL:[a-zA-z]+://[^\s]*

判断字符串是不是由数字组成: /^\d*$/

限制文本框只能输入数字和小数点(二位小数点):

/^\d*.?\d{0,2}$/

说明:开头有0个或者多个数字,(?表示匹配前一项0次或者多次)中间有0个或者1个小数点,小数点后面有0个或者最多2个数字

用户名正则: /^[\u4E00-\u9FA5\uf900-\ufa2d\w]{4,16}$/

匹配规则:只能是中文,英文,数字,下划线,4-16个字符

匹配中文字符正则:/[\u4E00-\u9FA5\uf900-\ufa2d]/

\w是 匹配英文,数字,下划线

匹配英文地址:/^[a-zA-Z][.a-zA-Z\s,0-9]*?[a-zA-Z]+/匹配规则:包含点,字母,空格,逗号,数字,但是开头和结尾必须为字母分析:开头必须为字母可以这样写/[a−zA−Z]/结尾必须为字母可以这样写:/[a−zA−Z]+/

中间包含点,字母,空格,逗号,数字的正则:/[.a-zA-Z\s,0-9]*?/

外面的*号是0个或者多个,后面的问号? 代表可有可无;有就匹配,没有就不匹配;

匹配价格:/^\d*(.\d{0,2})?$/

匹配规则: 开头有0个或者多个数字,中间可能有一个小数点,后面有可能有0-2位小数

单词的首字母大写:/\b(\w)|\s(\w)/g

验证日期格式:/^\d{4}[-\/]\d{1,2}[-\/]\d{1,2}$/

日期格式有2种 第一种是yyyy-mm-dd 或 yyyy/mm/dd

分析:月和天数可以有1位或者2位

此文源于: https://www.jb51.net/article/97901.htm

Guess you like

Origin www.cnblogs.com/xujunkai/p/11007434.html