System.Cats.Lol
System.Cats.Lol

Reputation: 1780

Regex: Exclude optional term from match

I'm trying to draft a regex that will match everything before the first : in a string, and exclude a specific term in the text right before the : if found. Call the term Grumble.

I want to match Foo in the string Foo: Bars.

I want to match Foo fuzz in Foo fuzz Grumble: Bars and moar bars.

I tried the pattern ^.*(?=(Grumble)?:), but it includes Grumble in the match in the second example above.

Upvotes: 1

Views: 1591

Answers (2)

degant
degant

Reputation: 4981

How about:

^.*?(?=Grumble|:)
  • .*? non-greedy match for any character
  • (?=Grumble|:) denotes a positive lookahead with two conditions
    • if Grumble is found then only capture until before Grumble
    • or if : is found then only capture until before :

Regex101 Demo

EDIT: Mis-interpreted the OP's ask a tiny bit. Thanks @revo for the clarification

Upvotes: 1

revo
revo

Reputation: 48751

You need a tempered [^:]:

^([^:](?!Grumble))*

Live demo

Explanation:

  • ^ Assert beginning of input string
  • ( Open a grouping
    • [^:] Any character except :
    • (?!Grumble) That's not followed by word Grumble
  • )* As much as possible

Upvotes: 2

Related Questions