Home > Software engineering >  Is it possible to use regular expressions to find a string that could have a stray space any place i
Is it possible to use regular expressions to find a string that could have a stray space any place i

Time:12-20

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.

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

CodePudding user response:

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

  • Related