1

I've been working on a regex problem for angularJs ng-pattern which needs:

  1. Cannot be blanks
  2. A minimum of 1 character and a maximum of 32 characters
  3. Spaces ONLY are not allowed
  4. Acceptable special characters(!@#$%&*-+=[]:;',.? )
  5. The answer is not case sensitive
  6. Combination of &# is not allowed
  7. Spaces at the beginning and the end of the answer should be trimmed.

This is my solution which covers all requirement but 6th:

([^a-zA-Z0-9!@#$%& *+=[\]:;',.?-])|(^\s*$)

Do you guys have any ideas?

5
  • Can you explain what "5. The answer is not case sensitive" means? Commented Apr 29, 2018 at 18:11
  • I think you need /^(?!\s*$)(?:(?!&#)[a-zA-Z0-9!@#$%&*+=[\]:;',.?\s-]){1,32}$/. However, I have no idea what your Req. 7 means. ng-pattern does not trim input text. Commented Apr 29, 2018 at 18:18
  • the only one that I couldn't figure out is #6 req. I can do 'string'.trim() to handle #7. And for #5, a-zA-Z covers that. Commented Apr 29, 2018 at 19:39
  • Ok, did you try my suggestion? See regex101.com/r/AuTmSj/1. It can also be ^(?!\s*$)(?!.*&#)[a-zA-Z0-9!@#$%&*+=[\]:;',.?\s-]{1,32}$ Commented Apr 29, 2018 at 20:00
  • Omg, that works great. Thank you, Wiktor. So, put the ?! at the beginning means to match the negate? Commented Apr 29, 2018 at 21:07

1 Answer 1

1

You may use

/^(?!\s*$)(?!.*&#)[a-zA-Z0-9!@#$%&*+=[\]:;',.?\s-]{1,32}$/

See the regex demo.

Details

  • ^ - start of string
  • (?!\s*$) - no 0+ whitespaces from start till end of string allowed
  • (?!.*&#) - no &# allowed after any 0+ chars
  • [a-zA-Z0-9!@#$%&*+=[\]:;',.?\s-]{1,32} - 1 to 32 allowed chars: ASCII digits, letters, whitespaces and some punctuation/symbols
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

3 Comments

Hey Wiktor, thanks for the help, just one more question. what about the #& combination? now, the &# combination is working now, but I tried to add another group of (?!#&), but it didn't work.
figure it out. /^(?!\s*$)(?:(?!&#|#&)[a-zA-Z0-9!@#$%&*+=[]:;’,.?\s-])+$/, there you go.
@user1070111 Or /^(?!\s*$)(?!.*#&)(?!.*&#)[a-zA-Z0-9!@#$%&*+=[\]:;',.?\s-]{1,32}$/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.