1

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.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
Deepak Yadav
  • 53
  • 1
  • 7

3 Answers3

6

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
$
Toto
  • 89,455
  • 62
  • 89
  • 125
0

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)
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
  • 2
    They want the **total** length to be less or equal to 20. – Toto Aug 24 '18 at 17:28
  • This is not working like it is just checking the constraint of last word if it is less than 20 it is allowing any string "wwwwwwwwwwwwwwwwwwwwwwwww www" is also working. Plus i want length of whole string less than 20. – Deepak Yadav Aug 24 '18 at 17:32
  • @DeepakYadav please confirm this works as expected. Thanks. – Steven Spungin Aug 24 '18 at 17:46
  • @StevenSpungin:It is working :) thanks also i used accidently different regex whixh seems to be working as well but i don't have the explaination why it is working:( I used /(\b(\w(\s\w+)*)\b){1,20}/ – Deepak Yadav Aug 24 '18 at 18:09
-1

Slight modification - try this (the {1, 20} is on the outside here:

(\b(\w+ (\s\w+)*)\b){1,20}
Paolo
  • 21,270
  • 6
  • 38
  • 69
combatc2
  • 1,215
  • 10
  • 10
  • 1
    They want the **total** length to be less or equal to 20. – Toto Aug 24 '18 at 17:36
  • It is working :) Is there any way to not let user enter name with space at the end like "deepak "should not be allowed. – Deepak Yadav Aug 24 '18 at 17:41
  • 1
    @DeepakYadav: No, it is not working, it matches `abcdefghi qsjhfjsqh fsjkhffjhg ` – Toto Aug 24 '18 at 17:44
  • @Toto : Right it is not working but I accidently used wrong regex which is working but now I don't know why it is working:( I used /(\b(\w(\s\w+)*)\b){1,20}/ – Deepak Yadav Aug 24 '18 at 17:51