admin管理员组

文章数量:1291144

I am looking for a regular expression which fulfil below conditions

  • Min 1 and Max 50 char
  • No spaces at the beginning and ending of string
  • Allow only one space, dot between 2 words.

I am using below expression which causes catastrophic backtracking issue. Expression -

/^[a-zA-Z]+(?:(?:|['_\. ])([a-zA-Z]*(\.\s)?[a-zA-Z])+)*$/

How can I prevent this issue?

I am looking for a regular expression which fulfil below conditions

  • Min 1 and Max 50 char
  • No spaces at the beginning and ending of string
  • Allow only one space, dot between 2 words.

I am using below expression which causes catastrophic backtracking issue. Expression -

/^[a-zA-Z]+(?:(?:|['_\. ])([a-zA-Z]*(\.\s)?[a-zA-Z])+)*$/

How can I prevent this issue?

Share Improve this question edited Oct 10, 2017 at 10:16 Rashmi Narware asked Oct 10, 2017 at 10:11 Rashmi NarwareRashmi Narware 411 silver badge5 bronze badges 4
  • 1 Try /^(?=.{1,50}$)[a-z]+(?:['_.\s][a-z]+)*$/i. – Wiktor Stribiżew Commented Oct 10, 2017 at 10:14
  • I updated my question, underscore will be there in pattern – Rashmi Narware Commented Oct 10, 2017 at 10:17
  • It would be good to have a set of test strings. Try them at regex101./r/TmJTBD/3 – Wiktor Stribiżew Commented Oct 10, 2017 at 10:18
  • /^(?=.{1,50}$)[a-z]+(?:['_.\s][a-z]+)*$/i. This worked for me . Thanks you so much. – Rashmi Narware Commented Oct 10, 2017 at 10:55
Add a ment  | 

1 Answer 1

Reset to default 9

You may use

/^(?=.{1,50}$)[a-z]+(?:['_.\s][a-z]+)*$/i

See the regex demo.

Details

  • ^ - start of string
  • (?=.{1,50}$) - there must be 1 to 50 chars in the string
  • [a-z]+ - 1 or more ASCII letters
  • (?:['_.\s][a-z]+)* - 0 or more sequences of
    • ['_.\s] - a ', _, . or whitespace
    • [a-z]+ - 1 or more ASCII letters
  • $ - end of string
  • /i - a case insensitive modifier.

本文标签: javascriptJs Regular expression for first nameStack Overflow