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

Is it possible to use regular expressions to find a string that could have a stray space any place in it?

I haven’t seen an answer to this specific question anywhere. My apologies if someone identifies it as a dupe. What I am wondering is: is it possible to search for:

abcdefghijk

matching any of the following:

a bcdefghijk
ab cdefghijk
abc defghijk
abcd efghijk
abcde fghijk
abcdef ghijk
abcdefg hijk
abcdefgh ijk
abcdefghi jk
abcdefghij k

I.e. I know the string I want to find, but it can end up with a stray space at any place.

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

Seems like this may be out of scope with regex, but wanted to be sure.

>Solution :

One approach would be to use a positive lookahead to find a space combined with a negative lookahead to not find a space.

Then let every character be followed by an optional space.

^(?=.* (?!.* ))?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?$
  • (?= – positive lookahead start
    • .* – anything followed by space
    • (?! – negative lookahead start
      • .* – anything followed by a space
    • ) – negative lookahead end
  • ) – positive lookahead end
  • ? – 0 or 1 match

Demo

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