Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular expression without "Double or more" spaces

I need a regular expression that allows:

  1. You cannot put a space at the beginning and end of a line
  2. There can only be one space between words

I had enough for something like "^[АЯ-Ёа-яё0-9′ ‘]+$", – but that’s not what I need.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This should work:

^(?! )(?!.*  )(?!.* $)[^\s].*$

Here’s a breakdown of the expression:

  • ^: Asserts the start of the line.
  • (?! ): Negative lookahead to disallow a space at the beginning of the line.
  • (?!.* ): Negative lookahead to disallow two or more consecutive spaces within the string.
  • (?!.* $): Negative lookahead to disallow a space at the end of the line.
  • [^\s]: Match any non-whitespace character.
  • .*: Match any character (except a newline) 0 or more times.
  • $: Asserts the end of the line.

I have put together a mini test on regex101.com.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading