Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement regular expressions in JavaScript

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you "JavaScript how to achieve regular expressions", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "JavaScript how to achieve regular expressions" this article.

What is a regular expression?

/ / regular expression (regular expression) is an object that describes character patterns

/ / JS defines RegExp classes to represent regular expressions

/ / both String and RegExp define functions that use regular expressions for powerful pattern matching and text retrieval and replacement

Second, create regular expressions

1. Create a regular expression

/ / JS provides two ways to create rules; one is to use the new operator, and the other is to use a literal quantity.

(1) .var box = new RegExp ('box'); / / the first parameter is a string

Var box = new RegExp ('box','ig'); / / the second parameter is the optional mode modifier

(2). Var box = / box/; / / use two backslashes directly

Var box = / box/ig; / / add mode modifier

2.RegExp object tests regular expressions

/ / the RegExp object contains two methods: test () and exec (), which are similar in function and are used to test string matching.

(1) .test (): finds whether a specified regular expression exists in a string and returns a Boolean value

/ / test () instance

Var pattern = new RegExp ('box','i'); / / create a regular

Var str = 'This is a Boxboy strings; / / create a string

Alert (pattern.test (str)); / / verify the match through the test () method

/ / use a statement to achieve regular matching

Alert (/ box/i.test ('This is a boxboxes'))

(2) .exec (): finds the specified regular expression in a string, returns an array of relevant information containing the lookup string if successful, and returns null if it fails.

Exec () instance

Var pattern = / box/i

Var str = 'This is a Boxbox'

Alert (pattern.exec (str)); / / matching returned an array

3.String object tests regular expressions

(1) .match (pattern): returns a substring or null in pattern

/ / math () method to get the matching array

Var pattern = / box/ig; / / Global is turned on

Var str = 'This is a Boxer, that is a Box toothing'

Alert (str.match (pattern)); / / get the array: [Box,Box]

(2) .search (pattern): returns the starting position of pattern in the string

Var pattern = / box/ig

Var str = 'This is a Boxer, that is a Box toothing'

Console.log (str.search (pattern)); / / 10 position search () returns as soon as it is found, otherwise-1 is returned

(3) .replace (pattern,replacement): replace pattern with replacement

Var pattern = / box/ig

Var str = 'This is a Boxboy' that is a Box too'

Console.log (str.replace (pattern,'Tom')); / / replace Box with Tom

(4) .split (pattern): returns an array of strings split according to the specified pattern

Var pattern = / / ig

Var str = 'This is a boxes, That is a Box too.'

Console.log (str.split (pattern)); / / splits spaces into an array

Three acquisition control

/ / regular expression metacharacters are characters with special meanings.

/ / they have some special functions that can control how patterns are matched.

/ / the metacharacter after the backslash will lose its special meaning

1. Metacharacter / meta-symbol matching

/ / character classes: single characters and numbers

. Match any character except a newline character

[a-z0-9] matches any character in the character set in parentheses

[^ a-z0-9] matches characters in a character set that is not in parentheses

\ d matching numbers

\ d match non-numeric

\ w match letters and numbers and _

\ W matches non-letters and numbers and _

/ / character class: White space character

\ 0 match null character

\ b match space characters

\ f match feed characters

\ nmatch newline character

\ r match carriage return character

\ t match configuration table character

\ s matches white space characters / spaces / tabs and newline characters

\ s matches non-white space characters

/ / character class: anchor character

^ match at the beginning of the line

Match at the end of the line

/ / character class: repeating characters

X? Match 0 or 1 x

X * match 0 or any number of x

X + matches at least one x

(xyz) + match at least one (xyz)

X {mdirection n} matches at least m, up to n x

/ / character class: alternate character

This | where | logo matches either this or where or logo

/ / character class: record character

$1 matches the contents of the first group

Example:

Pattern = / g.. glebind; / / ".": matches any character

Pattern = / g.roomgleswap; / / ". *": matches 0 or any number of characters

Pattern = / g [a murz] * gle/; / / [a murz] *: match any character in a murz

Pattern = / g [^ 0-9] * gle/; / / [^ 0-9] *: match any character other than 0-9

Pattern = / [Amurz] [Amurz] + /; / / [Amurz] +: matches the characters in Amurz one or more times

Pattern = / g\ wroomgleplash; / /\ wband: matches any number of all characters, digits and _

Pattern = / google\ dhammer; / /\ dstrings: match any number of digits

Pattern = /\ D {7,} /; / /\ D {7,}: match at least 7 non-digits

Pattern = / ^ google$/; / / "^": match from beginning; "$": match from end

Var pattern = / 8 (. *) 8 /

Var str = 'This is 8google8'

Str.match (pattern)

Console.log (RegExp.$1); / / get the string content in the first grouping

two。 Greed and inertia

+ +?

???

*?

{n} {n}?

{n,} {n,}?

{n,m} {n,m}?

Var pattern = / [a murz] + /; / / "?": greedy matching is turned off, only the first one is replaced.

Var str = 'abcdefg'

Alert (str.replace (pattern,'xxx')); / / = > xxxdefg

/ / use exec to return an array

Var pattern = / ^ [a murz] +\ s [0-9] {4} $/ I

Var str = 'google 2015'

Alert (pattern.exec (str) [0]); / / returns the entire string = > google 2015

Var pattern = / ^ [amerz] + / I

Var str = 'google 2015'

Alert (pattern.exec (str)); / / returns the matching letter = > google

/ / use special character matching

Var pattern = /\.\ [\ / b\] /

Var str ='.[ / b]'

Alert (pattern.test (str))

/ / use newline mode

Var pattern = / ^\ d+/mg

Var str = '1.baidu\ n2.google\ n3.bing.'

Var result = str.replace (pattern, "#")

Alert (result); / / # .baidu # .Google # .bing

Four commonly used rules

1. Check the zip code

/ / A total of 6 digits, the first digit cannot be 0

Var pattern = / [1-9] [0-9] {5} /

Var str = '224000'

Alert (pattern.test (str))

two。 Check the file package

/ / number + letter + _ +. + zip | rar | gz

Var pattern = / [\ w] +\ .zip | rar | gz/

Var str = '123.zip'

Alert (pattern.test (str))

3. Delete extra spaces

Var pattern = /\ sUnig; / / must be global in order to match all

Var str = '1112222333'

Var result = str.replace (pattern, "")

4. Delete leading and trailing spaces

Var pattern = / ^\ s impulse; / / forced first

Var str = 'goo gle'

Var result = str.replace (pattern, ""); / / remove the leading space

Pattern = /\ s forced tail

Result = result.replace (pattern, ""); / / remove the trailing space

5. Simple email verification

Var pattern = / ^ ([a-zA-Z0-9 _\.\ -] +) @ ([a-zA-Z0-0 _\.\ -] +)\. ([a-zA-Z] {2jue 4}) $/

Var str = 'abc123.com@gmail.com'

Alert (pattern.test (str))

These are all the contents of the article "how to implement regular expressions in JavaScript". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report