javascript - Correct syntax for regex to limit total length of matched group - Stack Overflow

I want to make a regex for matching name which can have more than one words.But at the same time I wan

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
 |  Show 3 more ments

3 Answers 3

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}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745441036a4627834.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信