Home > Web Front-end > JS Tutorial > body text

Taking stock of the pitfalls of square brackets in JavaScript regular expressions_javascript skills

WBOY
Release: 2016-05-16 15:10:29
Original
1152 people have browsed it

When using regular expressions in JavaScript, you need to pay attention to a pitfall inside the brackets, which is the problem of metacharacters within the brackets. I have stepped into a trap myself, and after searching online, many people have fallen into this trap, so I will give a rough summary.

The square brackets are called Character group(Character class) in regular expressions. Some books translate it as Character class, and others translate it into Character set . I think character groups are better. After all, class represents the "class" in object-oriented computer science. As the name suggests, a character group is a group of characters that represents a variety of characters that may appear in one position. Note that the emphasis here is to match only one position. (This paragraph is taken from - http://www.cnblogs.com/snandy/p/3662423.html)

used a place to get any characters, so I used [.n]*. As a result, if I test it, it will return true, but it is wrong to put it in the specific environment. . . . . . Oh my gosh, I can’t understand it.

Test decisively var testp = /xx>[.n]*/ testp.test("xx>asdfdfasd"); It is still true if you put "xx>" at the back, but it is true if you put "xx>" on both sides. false. Why is this? ? ? ? ? ?

So I re-created var testp = /(xx>[.n]*)/. Change it and add brackets to capture the matching string. Strung . After the test, RegExp.$1 was found to be empty. . . . . It's empty. . . . Why? ? ? ?

When the string parameter of test is changed to ("......."), this string of dots appears. Therefore, the dots in the square brackets only represent dots, not Anything else, not metacharacter division The meaning of a single character other than that. So I searched online:

“Many metacharacters have become ordinary characters in the character group” It has become ordinary characters instead of metacharacters, and there are other things like "?", "+", and "*" become ordinary characters once they are placed in square brackets.

So you still have to be careful about this pitfall. . . .

By the way, any character in can be replaced by [sS].

The [pit] in square brackets in the above inventory of javascript regular expressions is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template