-2

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.

chrismead
  • 2,163
  • 3
  • 24
  • 36
  • 1
    You could test for `a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k`, then inspect whether the total length of the resulting match is either `len(original_string)` or +1 – Mathias R. Jessen Dec 19 '22 at 15:21
  • well, if this is the best possible answer: /cats/ -> /c\s*a\s*t\s*s/ then it's a dupe. was hoping something better would be possible, but it does look like that question got a lot of views so I guess that is the best possible? – chrismead Dec 19 '22 at 15:22
  • 1
    The dupe will make it match strings with more than one space in them though. I got the impression you only want to allow max 1 space? – Ted Lyngmo Dec 19 '22 at 15:27
  • Happy to close as a dupe if anyone else wants to vote to close. – chrismead Feb 08 '23 at 18:36

1 Answers1

0

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

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Thanks, I like this better than the answer in the possible dupe. Hopefully I don't get too many downvotes to keep your awesome answer here. – chrismead Dec 19 '22 at 15:29
  • @chrismead Yeah :-) Perhaps there are more elegant solutions to this, but this was the first thing that popped up in my mind. It _feels_ like it should be possible to simplify it though. – Ted Lyngmo Dec 19 '22 at 15:31