LEARNING JAVASCRIPT - Trang 270

Repetition modifier

Description

Example

?

Zero or one. Equivalent to

{0,1}

.

/[a-z]\d?/i

matches letter followed by an

optional digit.

*

Zero or more (sometimes
called a “Klene star” or
“Klene closure”).

/[a-z]\d*/i

matches a letter followed by an

optional number, possibly consisting of multiple
digits.

+

One or more.

/[a-z]\d+/i

matches a letter followed by a

required number, possibly containing multiple
digits.

The Period Metacharacter and Escaping

In regex, the period is a special character that means “match anything” (except new‐

lines). Very often, this catch-all metacharacter is used to consume parts of the input

that you don’t care about. Let’s consider an example where you’re looking for a single

five-digit zip code, and then you don’t care about anything else on the rest of the line:

const

input

=

"Address: 333 Main St., Anywhere, NY, 55532. Phone: 555-555-2525."

;

const

match

=

input

.

match

(

/\d{5}.*/

);

You might find yourself commonly matching a literal period, such as the periods in a

domain name or IP address. Likewise, you may often want to match things that are

regex metacharacters, such as asterisks and parentheses. To escape any special regex

character, simply prefix it with a backslash:

const

equation

=

"(2 + 3.5) * 7"

;

const

match

=

equation

.

match

(

/\(\d \+ \d\.\d\) \* \d/

);

Many readers may have experience with

filename globbing, or being

able to use *.txt to search for “any text files.” The * here is a “wild‐

card” metacharacter, meaning it matches anything. If this is famil‐

iar to you, the use of * in regexes may confuse you, because it

means something completely different, and cannot stand alone.

The period in a regex is more closely related to the * in filename

globbing, except that it only matches a single character instead of a

whole string.

A True Wildcard

Because the period matches any character except newlines, how do you match any

character including newlines? (This comes up more often than you might think.)

There are lots of ways to do this, but probably the most common is

[\s\S]

. This

246 | Chapter 17: Regular Expressions

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.