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.
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.
Share Improve this question edited Aug 24, 2018 at 17:50 Steven Spungin 29.3k7 gold badges95 silver badges83 bronze badges asked Aug 24, 2018 at 17:23 Deepak YadavDeepak Yadav 531 silver badge7 bronze badges 8- 1 You are repeating the entire "names" block up to 20 times. – Niet the Dark Absol Commented Aug 24, 2018 at 17:30
- is it that you want the entire match to be a maximum of 20 chars? or do you want the length of each individual group to be a maximum of 20? – Ja Superior Commented Aug 24, 2018 at 17:32
- Posting some examples of inputs and their expected outputs could help – Ja Superior Commented Aug 24, 2018 at 17:33
- I want entire match to be a maximum of 20 chars. – Deepak Yadav Commented Aug 24, 2018 at 17:35
- 1 @LightnessRacesinOrbit this is not the way to solve problem you are literally saying if you can't drive then take a cab. – Deepak Yadav Commented Aug 24, 2018 at 18:10
3 Answers
Reset to default 7
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
$
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)
Slight modification - try this (the {1, 20} is on the outside here:
(\b(\w+ (\s\w+)*)\b){1,20}