简体   繁体   中英

JavaScript Regex curly braces

According to Eloquent JavaScript:

To indicate that a pattern should occur a precise number of times, use curly braces. Putting {4} after an element, for example, requires it to occur exactly four times.

However in Chrome, I get the following:

var str = /a{4}/
str.test('aaaaa')
// → true

The above paragraph implies str.test() should only return true when there are exactly 4 a's. Instead it returns true when there are at least 4 a's.

Also

It is also possible to specify a range this way: {2,4} means the element must occur at least twice and at most four times.

However, the same as above happens:

var str = /a{2,4}/
str.test('aaaaa')
// → true

Is there something I'm misunderstanding?

.test checks if there's any part of a string that matches your pattern:

This regex: /a{4}/

Can find 2 matches in a string of 5 a 's:

'aaaaa'
 ^^^^
  ^^^^

You'll want to tell the regex to strictly look at the start & end of the string:

 var str = /^a{4}$/ console.log(str.test('aaaaa')) 

Here, ^ and $ are "start" and "end" of string anchors

It returns true because there is a substring that fulfills the requirements. See documentation :

Use test() whenever you want to know whether a pattern is found in a string

You need to explicitly set beginning / end of string in the pattern:

var str = /^a{4}$/ 

str.test('aaaaa')

-> false

The /a{4}/ regular expression tests whether a string contains the aaaa substring. Specify start and end of line to test accurate match. Following snippet returns false :

var str = /^a{4}$/
str.test('aaaaa')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM