what the
what the

Reputation: 477

Match words surrounded by a character, but not the words inbetween those words

I'm trying to match this kind of pattern of strings containing words surrounded by a pair of colons (every line is a separate string):

:foo::bar:
:foo:
:foo: :bar::test:
:foo: :bar: :test:

but I want the regex to fail on these kind of patterns:

:foo:something:bar:
:foo:something
some :bar:
:foo: some:bar: thing
:foo: some :bar: thing

(Note that there can be 0 or more spaces between the words)

I tried using this regex:

re = /^(:.*?: ?)+$/gm

but it fails (as in it matches) on the second set of examples. Is there any way to somehow fail the regex when there are words inbetween or before/after the colon-surrounded words?

Upvotes: 0

Views: 500

Answers (1)

The fourth bird
The fourth bird

Reputation: 163352

You can repeat matching the words between : on the left and right if there have to be 1 or more word characters \w+ only.

Note that the . can also match : in the pattern that you tried.

^:\w+:(?: *:\w+:)*$

Regex demo

If you don't want to match : : : :

^(?:: *[^:\s]*[^:]*: *)+$
  • ^ Start of string
  • (?: Non capture group
    • : *[^:\s]* Match : optional spaces, a non whitespace char other than :
    • [^:]*: * Then optionally match any char except : and then match the :
  • )+ Close non capture group and repeat 1+ times
  • $ End of string

Regex demo

Upvotes: 1

Related Questions