Reputation: 53
I want to make a regex for matching name which can have more than one words. But at the same time I want to limit the total length to 20.
I used /\b(\w+ (\s\w+)*){1,20}\b/
.
I am getting the syntax but it is not checking word length constraint. Why?
Note: I am writing code in Javascript.
Upvotes: 1
Views: 5105
Reputation: 1263
Slight modification - try this (the {1, 20} is on the outside here:
(\b(\w+ (\s\w+)*)\b){1,20}
Upvotes: -2
Reputation: 29071
See Limit number of character of capturing group
This will still match, but limit at 20. (It took a few edits, but I think it got it...)
let rx = /(?=\b(\w+(\s\w+)*)\b).{1,20}/
let m = rx.exec('one two three four')
console.log(m[0])
console.log(m[0].length)
m = rx.exec('one two three four five six seven eight')
console.log(m[0])
console.log(m[0].length)
m = rx.exec('wwwww wwwww wwwww wwwww wwwww')
console.log(m[0])
console.log(m[0].length)
Upvotes: 0
Reputation: 91375
var test = [
"abc123 def456 ghi789",
"123456789012345678901",
"123456",
];
console.log(test.map(function (a) {
return a+' :'+/^(?=.{1,20}$)\w+(?: \w+)*$/.test(a);
}));
Explanation:
^ : beginning of line
(?=.{1,20}$) : positive lookahead, make sure we have no more than 20 characters
\w+ : 1 or more word character
(?: \w+)* : a space followed by 1 or more word char, may appear 0 or more times
$
Upvotes: 7